portinspector-1.0/0000755000175000017500000000000007614624020013624 5ustar julienjulienportinspector-1.0/snmp/0000755000175000017500000000000010433632554014605 5ustar julienjulienportinspector-1.0/snmp/SNMPBERCodec.java0000644000175000017500000002015407522113646017517 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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; public static final byte SNMPTRAP = (byte)0xA4; // 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 SNMPv2TRAP = (byte)0xA7; 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 SNMPTRAP: { return new SNMPTrapPDU(theTLV.value); } 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); } */ // single byte tag; extract value nextTLV.tag = enc[currentPos]; 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(); } }portinspector-1.0/snmp/SNMPBadValueException.java0000644000175000017500000000366707522113626021523 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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); } }portinspector-1.0/snmp/SNMPCounter32.java0000644000175000017500000000750307522113662017736 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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"); /** Initialize value to 0. */ public SNMPCounter32() { this(0); // initialize value to 0 } public SNMPCounter32(long newValue) { tag = SNMPBERCodec.SNMPCOUNTER32; 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. */ protected SNMPCounter32(byte[] enc) throws SNMPBadValueException { tag = SNMPBERCodec.SNMPCOUNTER32; 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 "); } }portinspector-1.0/snmp/SNMPCounter64.java0000644000175000017500000000754207522113673017750 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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"); /** Initialize value to 0. */ public SNMPCounter64() { this(0); // initialize value to 0 } public SNMPCounter64(long newValue) { tag = SNMPBERCodec.SNMPCOUNTER64; 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. */ protected SNMPCounter64(byte[] enc) throws SNMPBadValueException { tag = SNMPBERCodec.SNMPCOUNTER64; 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 "); } }portinspector-1.0/snmp/SNMPGauge32.java0000644000175000017500000000741607522113710017344 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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"); /** Initialize value to 0. */ public SNMPGauge32() { this(0); // initialize value to 0 } public SNMPGauge32(long newValue) { tag = SNMPBERCodec.SNMPGAUGE32; 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. */ protected SNMPGauge32(byte[] enc) throws SNMPBadValueException { tag = SNMPBERCodec.SNMPGAUGE32; 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 "); } }portinspector-1.0/snmp/SNMPGetException.java0000644000175000017500000000375107522113722020546 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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); } }portinspector-1.0/snmp/SNMPIPAddress.java0000644000175000017500000001206207522113744017765 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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 /** * Initialize to 0.0.0.0 */ public SNMPIPAddress() { // initialize to 0.0.0.0 tag = SNMPBERCodec.SNMPIPADDRESS; data = new byte[4]; for (int i = 0; i < 4; i++) data[i] = 0; } /** * Used to initialize from a string containing a standard "dotted" IP address. * @throws SNMPBadValueException Indicates an invalid string supplied: more than 4 components, * component values not between 0 and 255, etc. */ public SNMPIPAddress(String string) throws SNMPBadValueException { tag = SNMPBERCodec.SNMPIPADDRESS; this.data = parseIPAddress(string); } /** * 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 { tag = SNMPBERCodec.SNMPIPADDRESS; 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 "); } } }portinspector-1.0/snmp/SNMPInteger.java0000644000175000017500000001145707522113734017552 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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. */ protected 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. */ protected byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // write contents // boy, was THIS easy! Love that Java! byte[] data = value.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 value.toString(); // return new String(value.toString()); } }portinspector-1.0/snmp/SNMPMessage.java0000644000175000017500000001271007522113753017533 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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) { super(); Vector contents = new Vector(); contents.insertElementAt(new SNMPInteger(version), 0); contents.insertElementAt(new SNMPOctetString(community), 1); contents.insertElementAt(pdu, 2); try { this.setValue(contents); } catch (SNMPBadValueException e) { // can't happen! all supplied Vector elements are SNMP Object subclasses } } /** * Create an SNMP message with specified version, community, and trap pdu. * Use version = 0 for SNMP version 1, or version = 1 for enhanced capapbilities * provided through RFC 1157. */ public SNMPMessage(int version, String community, SNMPTrapPDU pdu) { super(); Vector contents = new Vector(); contents.insertElementAt(new SNMPInteger(version), 0); contents.insertElementAt(new SNMPOctetString(community), 1); contents.insertElementAt(pdu, 2); try { this.setValue(contents); } catch (SNMPBadValueException e) { // can't happen! all supplied Vector elements are SNMP Object subclasses } } /** * Construct an SNMPMessage from a received ASN.1 byte representation. * @throws SNMPBadValueException Indicates invalid SNMP message encoding supplied. */ protected 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() throws SNMPBadValueException { Vector contents = (Vector)(this.getValue()); Object pdu = contents.elementAt(2); if (!(pdu instanceof SNMPPDU)) { throw new SNMPBadValueException("Wrong PDU type in message: expected SNMPPDU, have " + pdu.getClass().toString()); } return (SNMPPDU)pdu; } public SNMPTrapPDU getTrapPDU() throws SNMPBadValueException { Vector contents = (Vector)(this.getValue()); Object pdu = contents.elementAt(2); if (!(pdu instanceof SNMPTrapPDU)) { throw new SNMPBadValueException("Wrong PDU type in message: expected SNMPTrapPDU, have " + pdu.getClass().toString()); } return (SNMPTrapPDU)pdu; } }portinspector-1.0/snmp/SNMPNSAPAddress.java0000644000175000017500000001170607522113762020222 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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 /** * Initialize address to 0.0.0.0.0.0. */ public SNMPNSAPAddress() { tag = SNMPBERCodec.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 { tag = SNMPBERCodec.SNMPNSAPADDRESS; data = parseNSAPAddress(string); } /** * 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 { tag = SNMPBERCodec.SNMPNSAPADDRESS; 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 "); } } }portinspector-1.0/snmp/SNMPNull.java0000644000175000017500000000475007522113772017067 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package snmp; /** * Object representing the SNMP Null data type. */ public class SNMPNull extends SNMPObject { protected byte tag = SNMPBERCodec.SNMPNULL; /** * 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. */ protected 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"); } }portinspector-1.0/snmp/SNMPObject.java0000644000175000017500000000450507522114006017350 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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; /** * Should return an appropriate human-readable representation of the stored value. */ public abstract String toString(); /** * Must return the BER byte encoding (type, length, value) of the SNMP object. */ protected abstract byte[] getBEREncoding(); }portinspector-1.0/snmp/SNMPObjectIdentifier.java0000644000175000017500000002261407522114015021354 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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 protected byte tag = SNMPBERCodec.SNMPOBJECTIDENTIFIER; /** * 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. */ protected 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. */ protected 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; } }portinspector-1.0/snmp/SNMPOctetString.java0000644000175000017500000001235307522114024020407 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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. */ protected 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; } }portinspector-1.0/snmp/SNMPPDU.java0000644000175000017500000001413707522114033016574 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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 { /** * 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(byte pduType, int requestID, int errorStatus, int errorIndex, SNMPSequence varList) throws SNMPBadValueException { super(); Vector contents = new Vector(); tag = 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. */ protected SNMPPDU(byte[] enc, byte pduType) throws SNMPBadValueException { tag = 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(); } }portinspector-1.0/snmp/SNMPSequence.java0000644000175000017500000001446007522114043017714 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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 byte tag = 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. */ protected 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. */ protected 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(tag); 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; } }portinspector-1.0/snmp/SNMPSetException.java0000644000175000017500000000375707522114052020565 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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); } }portinspector-1.0/snmp/SNMPTLV.java0000644000175000017500000000330607522114073016611 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package snmp; /** * Utility class holding components of an ASN.1 (type, length, value) triple. */ class SNMPTLV { byte tag; int totalLength; byte[] value; }portinspector-1.0/snmp/SNMPTimeTicks.java0000644000175000017500000000377407522114062020047 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package snmp; /** * SNMP datatype used to represent time value. Just extension of SNMPInteger. */ public class SNMPTimeTicks extends SNMPInteger { public SNMPTimeTicks() { this(0); // initialize value to 0 } public SNMPTimeTicks(long value) { super(value); tag = SNMPBERCodec.SNMPTIMETICKS; } protected SNMPTimeTicks(byte[] enc) throws SNMPBadValueException { super(enc); tag = SNMPBERCodec.SNMPTIMETICKS; } }portinspector-1.0/snmp/SNMPUInteger32.java0000644000175000017500000000740007522114124020027 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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"); /** * 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) { tag = SNMPBERCodec.SNMPUINTEGER32; 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. */ protected SNMPUInteger32(byte[] enc) throws SNMPBadValueException { tag = SNMPBERCodec.SNMPUINTEGER32; 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 "); } }portinspector-1.0/snmp/SNMPUnknownObject.java0000644000175000017500000000613607522114134020734 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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; protected byte tag = SNMPBERCodec.SNMPUNKNOWNOBJECT; /** * 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. */ protected 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); } }portinspector-1.0/snmp/SNMPVarBindList.java0000644000175000017500000000516507522114172020332 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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; } }portinspector-1.0/snmp/SNMPVariablePair.java0000644000175000017500000000502407522114202020476 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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); } }portinspector-1.0/snmp/SNMPv1CommunicationInterface.java0000644000175000017500000005724007601631630023050 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ 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; // largest size for datagram packet payload; based on // RFC 1157, need to handle messages of at least 484 bytes 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 value 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; } /** * Retrieve all MIB variable values whose OIDs start with the supplied baseID. Since the entries of * an SNMP table have the form .., this will retrieve all of the table * data as an SNMPVarBindList object consisting of sequence of SNMPVariablePairs. * Uses SNMPGetNextRequests to retrieve variable values in sequence. * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException */ public SNMPVarBindList retrieveMIBTable(String baseID) throws IOException, SNMPBadValueException, SNMPGetException { // 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; String currentID = baseID; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(currentID); while (errorStatus == 0) { 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); /* System.out.println("Request bytes:"); for (int i = 0; i < messageEncoding.length; ++i) { System.out.print(getHex(messageEncoding[i]) + " "); } */ dSocket.send(outPacket); DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); 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, just break - could be there are no additional OIDs if (receivedPDU.getErrorStatus() != 0) { break; //throw new SNMPGetException("OID following " + requestedObjectIdentifier + " not available for retrieval"); } varList = receivedPDU.getVarBindList(); SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0)); SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0)); SNMPObject newValue = newPair.getSNMPObjectAt(1); // now see if retrieved ID starts with table base; if not, done with table - break String newOIDString = (String)newObjectIdentifier.toString(); if (!newOIDString.startsWith(baseID)) break; retrievedVars.addSNMPObject(newPair); requestedObjectIdentifier = newObjectIdentifier; 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; } */ }portinspector-1.0/snmp/package.html0000644000175000017500000000362407503646713017101 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. portinspector-1.0/snmp/SNMPv1TrapInterface.java0000644000175000017500000001706107522114156021147 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package snmp; import java.io.*; import java.math.*; import java.net.*; import java.util.*; /** * The class SNMPv1TrapReceiver implements a "listener" for trap messages sent from remote SNMP entities. * The approach is that from version 1 of SNMP, using no encryption of data. Communication occurs * via UDP, using port 162, the standard SNMP trap port. * * Applications utilize this class with classes which implement the SNMPTrapListener interface. These * must provide a processTrap() method, and are registered/deregistered with this class through its * addTrapListener() and removeTrapListener methods. */ public class SNMPv1TrapInterface implements Runnable { public static final int SNMP_TRAP_PORT = 162; // largest size for datagram packet payload; based on // RFC 1157, need to handle messages of at least 484 bytes public static final int MAXSIZE = 512; private DatagramSocket dSocket; private Thread receiveThread; private Vector listenerVector; /** * Construct a new trap receiver object to receive traps from remote SNMP hosts. * This version will accept messages from all hosts using any community name. */ public SNMPv1TrapInterface() throws SocketException { dSocket = new DatagramSocket(SNMP_TRAP_PORT); listenerVector = new Vector(); receiveThread = new Thread(this); } public void addTrapListener(SNMPTrapListener listener) { // see if listener already added; if so, ignore for (int i = 0; i < listenerVector.size(); i++) { if (listener == listenerVector.elementAt(i)) { return; } } // if got here, it's not in the list; add it listenerVector.add(listener); } public void removeTrapListener(SNMPTrapListener listener) { // see if listener in list; if so, remove, if not, ignore for (int i = 0; i < listenerVector.size(); i++) { if (listener == listenerVector.elementAt(i)) { listenerVector.removeElementAt(i); break; } } } /** * Start listening for trap messages. */ public void startReceiving() { // if receiveThread not already running, start it if (!receiveThread.isAlive()) { receiveThread = new Thread(this); receiveThread.start(); } } /** * Stop listening for trap messages. */ public void stopReceiving() throws SocketException { // interrupt receive thread so it will die a natural death receiveThread.interrupt(); } /** * Send the supplied trap pdu to the specified host, using the supplied version number * and community name. Use version = 0 for SNMP version 1, or version = 1 for enhanced * capabilities provided through RFC 1157. */ public void sendTrap(int version, InetAddress hostAddress, String community, SNMPTrapPDU pdu) throws IOException { 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, SNMP_TRAP_PORT); /* System.out.println("Message bytes length (out): " + outPacket.getLength()); System.out.println("Message bytes (out):"); for (int i = 0; i < messageEncoding.length; ++i) { System.out.print(hexByte(messageEncoding[i]) + " "); } System.out.println("\n"); */ dSocket.send(outPacket); } /** * Send the supplied trap pdu to the specified host, using the supplied community name and * using 0 for the version field in the SNMP message (corresponding to SNMP version 1). */ public void sendTrap(InetAddress hostAddress, String community, SNMPTrapPDU pdu) throws IOException { int version = 0; sendTrap(version, hostAddress, community, pdu); } /** * The run() method for the trap interface's listener. Just waits for trap messages to * come in on port 162, then dispatches the retrieved SNMPTrapPDU to each of the * registered SNMPTrapListeners by calling their processTrap() methods. */ public void run() { int errorStatus = 0; int errorIndex = 0; try { while (!receiveThread.isInterrupted()) { DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); /* System.out.println("Message bytes length (in): " + inPacket.getLength()); System.out.println("Message bytes (in):"); for (int i = 0; i < encodedMessage.length; ++i) { System.out.print(hexByte(encodedMessage[i]) + " "); } System.out.println("\n"); */ SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); SNMPTrapPDU receivedPDU = receivedMessage.getTrapPDU(); // pass the received trap PDU to the processTrap method of any listeners for (int i = 0; i < listenerVector.size(); i++) { SNMPTrapListener listener = (SNMPTrapListener)listenerVector.elementAt(i); listener.processTrap(receivedPDU); } } } catch (IOException e) { // do nothing for now... } catch (SNMPBadValueException e) { // do nothing for now... } } 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; } 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; } }portinspector-1.0/snmp/SNMPTrapPDU.java0000644000175000017500000002152107522114114017416 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package snmp; import java.util.*; import java.io.*; import java.math.*; /** * The SNMPTrapPDU class represents an SNMP Trap PDU from RFC 1157, as indicated below. This * forms the payload of an SNMP Trap 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 } Trap-PDU ::= [4] IMPLICIT SEQUENCE { enterprise -- type of object generating -- trap, see sysObjectID in [5] OBJECT IDENTIFIER, agent-addr -- address of object generating NetworkAddress, -- trap generic-trap -- generic trap type INTEGER { coldStart(0), warmStart(1), linkDown(2), linkUp(3), authenticationFailure(4), egpNeighborLoss(5), enterpriseSpecific(6) }, specific-trap -- specific code, present even INTEGER, -- if generic-trap is not -- enterpriseSpecific time-stamp -- time elapsed between the last TimeTicks, -- (re)initialization of the network -- entity and the generation of the trap variable-bindings -- "interesting" information VarBindList } -- variable bindings VarBind ::= SEQUENCE { name ObjectName, value ObjectSyntax } VarBindList ::= SEQUENCE OF VarBind END */ public class SNMPTrapPDU extends SNMPSequence { /** * Create a new Trap PDU of the specified type, with given request ID, error status, and error index, * and containing the supplied SNMP sequence as data. */ public SNMPTrapPDU(SNMPObjectIdentifier enterpriseOID, SNMPIPAddress agentAddress, int genericTrap, int specificTrap, SNMPTimeTicks timestamp, SNMPSequence varList) throws SNMPBadValueException { super(); tag = SNMPBERCodec.SNMPTRAP; Vector contents = new Vector(); contents.addElement(enterpriseOID); contents.addElement(agentAddress); contents.addElement(new SNMPInteger(genericTrap)); contents.addElement(new SNMPInteger(specificTrap)); contents.addElement(timestamp); contents.addElement(varList); this.setValue(contents); } /** * Create a new Trap PDU of the specified type, with given request ID, error status, and error index, * and containing an empty SNMP sequence (VarBindList) as additional data. */ public SNMPTrapPDU(SNMPObjectIdentifier enterpriseOID, SNMPIPAddress agentAddress, int genericTrap, int specificTrap, SNMPTimeTicks timestamp) throws SNMPBadValueException { super(); tag = SNMPBERCodec.SNMPTRAP; Vector contents = new Vector(); contents.addElement(enterpriseOID); contents.addElement(agentAddress); contents.addElement(new SNMPInteger(genericTrap)); contents.addElement(new SNMPInteger(specificTrap)); contents.addElement(timestamp); contents.addElement(new SNMPVarBindList()); 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. */ protected SNMPTrapPDU(byte[] enc) throws SNMPBadValueException { tag = SNMPBERCodec.SNMPTRAP; 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(5)); } /** * A utility method that extracts the enterprise OID from this PDU. */ public SNMPObjectIdentifier getEnterpriseOID() { Vector contents = (Vector)(this.getValue()); return (SNMPObjectIdentifier)contents.elementAt(0); } /** * A utility method that extracts the sending agent address this PDU. */ public SNMPIPAddress getAgentAddress() { Vector contents = (Vector)(this.getValue()); return (SNMPIPAddress)contents.elementAt(1); } /** * A utility method that returns the generic trap code for this PDU. */ public int getGenericTrap() { Vector contents = (Vector)(this.getValue()); return ((BigInteger)((SNMPInteger)(contents.elementAt(2))).getValue()).intValue(); } /** * A utility method that returns the specific trap code for this PDU. */ public int getSpecificTrap() { Vector contents = (Vector)(this.getValue()); return ((BigInteger)((SNMPInteger)(contents.elementAt(3))).getValue()).intValue(); } /** * A utility method that returns the timestamp for this PDU. */ public long getTimestamp() { Vector contents = (Vector)(this.getValue()); return ((BigInteger)((SNMPTimeTicks)(contents.elementAt(4))).getValue()).longValue(); } }portinspector-1.0/snmp/SNMPTrapListener.java0000644000175000017500000000403207522114104020550 0ustar julienjulien/* * SNMP Package * * Copyright (C) 2002, Jonathan Sevy * * This is free software. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package snmp; /** * SNMPv1TrapListener is an interface that must be implemented by any class which wishes * to act as a "listener" for trap messages sent from remote SNMP entities using the SNMPv1TrapInterface * class. The SNMPv1TrapInterface class listens for trap messages, and passes any it receives on to * SNMPTrapListener subclasses that have registered with it through its addTrapListener() method. */ public interface SNMPTrapListener { public void processTrap(SNMPTrapPDU trapPDU); }portinspector-1.0/JTextAreaWriter.java0000644000175000017500000000302107614603541017514 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.io.*; import javax.swing.text.*; public class JTextAreaWriter extends Writer { private JTextComponent textArea; public JTextAreaWriter(JTextComponent textArea) { this.textArea = textArea; } public void flush() { // do nothing } public void close() { // ditto } public void write (char[] charArray, int start, int end) { String messageString = new String(charArray); messageString = messageString.substring(start, end); textArea.setText(messageString); } public void write (String messageString) { textArea.setText(messageString); } }portinspector-1.0/COPYING0000444000175000017500000004363107503646703014675 0ustar julienjulien GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy 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 Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. portinspector-1.0/AboutDialog.java0000755000175000017500000001123107614610570016667 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 java.awt.event.*; import javax.swing.*; import java.io.*; import java.applet.*; public class AboutDialog extends JDialog implements Runnable, ActionListener { private JLabel aboutLabel1 = new JLabel("AirPort Port Inspector"); private JLabel aboutLabel2 = new JLabel("J. Sevy"); private JLabel aboutLabel3 = new JLabel("January, 2003"); private JLabel aboutLabel4 = new JLabel(""); private JLabel aboutLabel5 = new JLabel(""); private String descriptionString = "Who's surfing through _your_ ports? "; private JButton okButton; Thread displayThread; public AboutDialog(JFrame parent) { super(parent, "About Airport Port Inspector", true /*modal*/); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setUpDisplay(); this.setLocation(Math.round((parent.getSize().width - this.getSize().width)/2), Math.round((parent.getSize().height - this.getSize().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; aboutLabel1.setBackground(Color.white); aboutLabel2.setBackground(Color.white); aboutLabel3.setBackground(Color.white); aboutLabel4.setBackground(Color.white); aboutLabel5.setBackground(Color.white); okButton = new JButton("OK"); okButton.setActionCommand("ok"); okButton.addActionListener(this); okButton.setBackground(Color.white); this.getRootPane().setDefaultButton(okButton); JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(theLayout); aboutPanel.setBackground(Color.white); 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); c.gridx = 1; c.gridy = 5; theLayout.setConstraints(aboutLabel5, c); aboutPanel.add(aboutLabel5); this.getContentPane().setLayout(theLayout); this.getContentPane().setBackground(Color.white); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(aboutPanel, c); this.getContentPane().add(aboutPanel); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(okButton, c); this.getContentPane().add(okButton); this.pack(); this.setSize(300, 200); } public void actionPerformed(ActionEvent theEvent) // respond to button pushes, menu selections { String command = theEvent.getActionCommand(); if (command.equals("ok")) { this.hide(); } } public void run() { try { // simultaneously, write message out a character at a time... int numChars = descriptionString.length(); for (int i = 0; i < numChars; i++) { aboutLabel4.setText(descriptionString.substring(0,i)); Thread.currentThread().sleep(60); } } catch(Exception e) { // don't bother informing of exception; just exit... //System.out.println(e); } // later! } }portinspector-1.0/PortInspector.java0000644000175000017500000005566607614603737017340 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 PortInspector extends JFrame implements ActionListener, Runnable { JButton newPreferencesButton, discoverDevicesButton; JRadioButton simpleDisplayButton, detailedDisplayButton; JTextField airportInternalIPField; JTextField airportExternalIPField, airportNameField, airportLocationField; JPanel hostPanel; MenuBar theMenubar; Menu fileMenu; MenuItem quitItem, aboutItem, savePreferencesItem; JTextArea messagesArea; JTextAreaWriter messagesAreaWriter; PortMapTable portMapTable; Thread inspectionThread; Preferences preferences; boolean preferencesSaved = true; SNMPv1CommunicationInterface communicationInterface; String portMapBaseID = "1.3.6.1.4.1.731.100.3.1.1"; String arpInfoTableOID = "1.3.6.1.2.1.4.22.1"; private Vector changeListeners; PortInfoTreeMap currentInfo; // WindowCloseAdapter to catch window close-box closings private class WindowCloseAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public PortInspector() { // read any settings that have previously been saved readSettings(); changeListeners = new Vector(); currentInfo = new PortInfoTreeMap(); // create thread, but don't start it inspectionThread = new Thread(this); setUpDisplay(); // create Writer interface into messages area for use by change listeners messagesAreaWriter = new JTextAreaWriter(messagesArea); this.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 = this.getSize(); dim.height += 20; dim.width += 20; this.setSize(dim); this.show(); // put up dialog to solicit new settings if (getPreferences() == false) { messagesArea.setText("Problem with supplied information; set options again"); } } public void addChangeListener(PortInfoChangeListener changeListener) { if (!changeListeners.contains(changeListener)) changeListeners.add(changeListener); } public void removeChangeListener(PortInfoChangeListener changeListener) { if (changeListeners.contains(changeListener)) changeListeners.remove(changeListener); } private void setUpDisplay() { // 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()); this.setTitle("Port Inspector"); this.getRootPane().setBorder(new BevelBorder(BevelBorder.RAISED)); theMenubar = new MenuBar(); this.setMenuBar(theMenubar); fileMenu = new Menu("File"); aboutItem = new MenuItem("About..."); aboutItem.setActionCommand("about"); aboutItem.addActionListener(this); fileMenu.add(aboutItem); savePreferencesItem = new MenuItem("Save settings"); savePreferencesItem.setActionCommand("save preferences"); savePreferencesItem.addActionListener(this); fileMenu.add(savePreferencesItem); fileMenu.addSeparator(); quitItem = new MenuItem("Quit"); quitItem.setShortcut(new MenuShortcut('q')); quitItem.setActionCommand("quit"); quitItem.addActionListener(this); fileMenu.add(quitItem); theMenubar.add(fileMenu); JLabel airportInternalIPLabel = new JLabel("Base station LAN address:"); airportInternalIPField = new JTextField(10); airportInternalIPField.setText("10.0.1.1"); airportInternalIPField.setEditable(false); JLabel airportExternalIPLabel = new JLabel("Base station WAN address:"); airportExternalIPField = new JTextField(10); airportExternalIPField.setEditable(false); JLabel airportNameLabel = new JLabel("Base station name:"); airportNameField = new JTextField(20); airportNameField.setEditable(false); JLabel airportLocationLabel = new JLabel("Base station location:"); airportLocationField = new JTextField(20); airportLocationField.setEditable(false); simpleDisplayButton = new JRadioButton("Simple display"); simpleDisplayButton.setActionCommand("simple display"); simpleDisplayButton.addActionListener(this); detailedDisplayButton = new JRadioButton("Detailed display"); detailedDisplayButton.setActionCommand("detailed display"); detailedDisplayButton.addActionListener(this); ButtonGroup displayButtonGroup = new ButtonGroup(); displayButtonGroup.add(simpleDisplayButton); displayButtonGroup.add(detailedDisplayButton); if (preferences.displayType == PortMapTable.DETAILED) detailedDisplayButton.setSelected(true); else simpleDisplayButton.setSelected(true); newPreferencesButton = new JButton("Change base station"); newPreferencesButton.setActionCommand("new preferences"); newPreferencesButton.addActionListener(this); discoverDevicesButton = new JButton("Discover devices"); discoverDevicesButton.setActionCommand("discover devices"); discoverDevicesButton.addActionListener(this); portMapTable = new PortMapTable(currentInfo, preferences.displayType); // 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; Insets theMargin = new Insets(2,2,2,2); c.insets = theMargin; c.anchor = GridBagConstraints.CENTER; c.weightx = .5; c.weighty = .5; // layout buttons in panel JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(theLayout); c.gridwidth = 2; c.gridx = 1; c.gridy = 1; theLayout.setConstraints(newPreferencesButton, c); buttonPanel.add(newPreferencesButton); /* c.gridx = 2; c.gridy = 1; theLayout.setConstraints(discoverDevicesButton, c); buttonPanel.add(discoverDevicesButton); */ c.gridwidth = 1; c.gridx = 1; c.gridy = 2; theLayout.setConstraints(simpleDisplayButton, c); buttonPanel.add(simpleDisplayButton); c.gridx = 2; c.gridy = 2; theLayout.setConstraints(detailedDisplayButton, c); buttonPanel.add(detailedDisplayButton); // layout host info in panel hostPanel = new JPanel(); hostPanel.setLayout(theLayout); c.anchor = GridBagConstraints.EAST; c.gridx = 1; c.gridy = 1; theLayout.setConstraints(airportInternalIPLabel, c); hostPanel.add(airportInternalIPLabel); c.anchor = GridBagConstraints.WEST; c.gridx = 2; c.gridy = 1; theLayout.setConstraints(airportInternalIPField, c); hostPanel.add(airportInternalIPField); c.anchor = GridBagConstraints.EAST; c.gridx = 1; c.gridy = 2; theLayout.setConstraints(airportExternalIPLabel, c); hostPanel.add(airportExternalIPLabel); c.anchor = GridBagConstraints.WEST; c.gridx = 2; c.gridy = 2; theLayout.setConstraints(airportExternalIPField, c); hostPanel.add(airportExternalIPField); c.anchor = GridBagConstraints.EAST; c.gridx = 1; c.gridy = 3; theLayout.setConstraints(airportNameLabel, c); hostPanel.add(airportNameLabel); c.anchor = GridBagConstraints.WEST; c.gridx = 2; c.gridy = 3; theLayout.setConstraints(airportNameField, c); hostPanel.add(airportNameField); c.anchor = GridBagConstraints.EAST; c.gridx = 1; c.gridy = 4; theLayout.setConstraints(airportLocationLabel, c); hostPanel.add(airportLocationLabel); c.anchor = GridBagConstraints.WEST; c.gridx = 2; c.gridy = 4; theLayout.setConstraints(airportLocationField, c); hostPanel.add(airportLocationField); c.anchor = GridBagConstraints.CENTER; JPanel messagesPanel = new JPanel(); messagesPanel.setLayout(theLayout); messagesArea = new JTextArea(6,40); JScrollPane messagesScroll = new JScrollPane(messagesArea); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.weighty = 0; c.gridx = 1; c.gridy = 1; JLabel messagesLabel = new JLabel("Messages:"); theLayout.setConstraints(messagesLabel, c); messagesPanel.add(messagesLabel); c.fill = GridBagConstraints.BOTH; c.weightx = .5; c.weighty = .5; c.gridx = 1; c.gridy = 2; theLayout.setConstraints(messagesScroll, c); messagesPanel.add(messagesScroll); this.getContentPane().setLayout(theLayout); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.weighty = 0; c.gridx = 1; c.gridy = 1; theLayout.setConstraints(hostPanel, c); this.getContentPane().add(hostPanel); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(buttonPanel, c); this.getContentPane().add(buttonPanel); c.fill = GridBagConstraints.BOTH; c.weightx = .5; c.weighty = .5; c.gridx = 1; c.gridy = 3; theLayout.setConstraints(portMapTable, c); this.getContentPane().add(portMapTable); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = .5; c.weighty = .5; c.gridx = 1; c.gridy = 4; theLayout.setConstraints(messagesPanel, c); this.getContentPane().add(messagesPanel); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.weighty = 0; c.gridx = 1; c.gridy = 5; JLabel authorLabel = new JLabel(" Version 1.0 J. Sevy, January 2003 "); authorLabel.setFont(new Font("SansSerif", Font.ITALIC, 8)); 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.equals("quit")) { if (preferencesSaved == false) { // put up dialog to ask if settings should be saved if (JOptionPane.showConfirmDialog(this, "Save current settings?","Save settings?",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { saveSettings(); } } System.exit(0); } if (command == "about") { AboutDialog aboutDialog = new AboutDialog(this); } if (command.equals("discover devices")) { AirportDiscoverer discoverer = new AirportDiscoverer(); } if (command.equals("simple display")) { portMapTable.setDisplayType(PortMapTable.SIMPLE); } if (command.equals("detailed display")) { portMapTable.setDisplayType(PortMapTable.DETAILED); } if (command == "new preferences") { getPreferences(); } if (command.equals("save preferences")) { saveSettings(); } } private boolean getPreferences() { PreferencesDialog theDialog = new PreferencesDialog(this, preferences); if (!theDialog.isCancelled()) { // stop thread if needed if (inspectionThread.isAlive()) { inspectionThread.interrupt(); } // get preferences Preferences newPreferences = theDialog.getPreferences(); try { if (!newPreferences.equals(preferences)) preferencesSaved = false; InetAddress airportInternalIPAddress = InetAddress.getByName(newPreferences.ipAddress); airportInternalIPField.setText(newPreferences.ipAddress); // create new SNMP communication interface communicationInterface = new SNMPv1CommunicationInterface(0, airportInternalIPAddress, newPreferences.password); // remove current action object //this.removeChangeListener(changeEmailer); // create and add new action object //changeEmailer = new AirportInfoChangeEmailer(newPreferences.emailAddress, newPreferences.smtpHost, messagesAreaWriter); //changeListeners.add(changeEmailer); preferences = newPreferences; inspectionThread = new Thread(this); inspectionThread.start(); return true; } catch(UnknownHostException e) { JOptionPane.showMessageDialog(this, "Unknown host name supplied."); } catch(Exception e) { JOptionPane.showMessageDialog(this, "Error setting new preferences: " + e); } } return false; } private PortInfoTreeMap getInfo() throws IllegalArgumentException, SocketException, IOException, SNMPGetException, SNMPBadValueException { SNMPVarBindList varBindList; String valueString; varBindList = communicationInterface.getMIBEntry("1.3.6.1.2.1.1.5.0"); valueString = ((SNMPSequence)varBindList.getSNMPObjectAt(0)).getSNMPObjectAt(1).toString(); airportNameField.setText(valueString); varBindList = communicationInterface.getMIBEntry("1.3.6.1.2.1.1.6.0"); valueString = ((SNMPSequence)varBindList.getSNMPObjectAt(0)).getSNMPObjectAt(1).toString(); airportLocationField.setText(valueString); // get WAN IP address (corresponding to interface 3) varBindList = communicationInterface.retrieveMIBTable("1.3.6.1.2.1.4.20.1"); valueString = getInterfaceAddress(varBindList, 3); airportExternalIPField.setText(valueString); // now fetch portmap table SNMPVarBindList snmpPortMapInfo = communicationInterface.retrieveMIBTable(portMapBaseID); PortInfoTreeMap portInfoHashtable = new PortInfoTreeMap(snmpPortMapInfo); //System.out.println("SNMP table:"); //System.out.println(snmpPortMapInfo.toString()); // now fetch arp info table, to get MAC addresses SNMPVarBindList snmpArpInfo = communicationInterface.retrieveMIBTable(arpInfoTableOID); ArpInfoTreeMap ArpInfoTreeMap = new ArpInfoTreeMap(snmpArpInfo); portInfoHashtable.setMACAddresses(ArpInfoTreeMap); return portInfoHashtable; } public String getInterfaceAddress(SNMPVarBindList varBindList, int interfaceIndex) { class InterfaceInfo { String ipAddress; int interfaceIndex; } TreeMap interfaceInfoMap = new TreeMap(); // make list of interface index / IP address pairs; // find entry corresponding to interface 2, and return its IP address if (varBindList.size() > 0) { int i = 0; SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); String oid = snmpOID.toString(); String oidBase = "1.3.6.1.2.1.4.20.1.1"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // add a new InterfaceInfo object to hashtable, hashed by index interfaceInfoMap.put(tableIndex, new InterfaceInfo()); // this entry also gives IP address InterfaceInfo interfaceInfo = (InterfaceInfo)interfaceInfoMap.get(tableIndex); SNMPIPAddress ipAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); interfaceInfo.ipAddress = ipAddress.toString(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.2.1.4.20.1.2"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable InterfaceInfo interfaceInfo = (InterfaceInfo)interfaceInfoMap.get(tableIndex); SNMPInteger snmpInterfaceIndex = (SNMPInteger)variablePair.getSNMPObjectAt(1); interfaceInfo.interfaceIndex = ((BigInteger)snmpInterfaceIndex.getValue()).intValue(); // see if have entry for desired interface index if (interfaceInfo.interfaceIndex == interfaceIndex) { return interfaceInfo.ipAddress; } i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } } // if get here, didn't find it... return ""; } private void refreshInfoDisplay(PortInfoTreeMap newInfo) { // update displayed info //messagesArea.append(newInfo.toString()); portMapTable.setInfo(newInfo); } /* 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; } private String printHexBytes(byte[] bytes) { String returnString = new String(); for(int i = 0; i < bytes.length; i++) { returnString += hexByte(bytes[i]) + " "; if (((i+1)%16) == 0) returnString += "\n"; } return returnString; } private static boolean arraysEqual(byte[] a, byte[] b) { if (a.length != b.length) { return false; } else { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } } return true; } private static byte[] maskBytes(byte[] inBytes, byte[] mask) { byte[] maskedBytes = new byte[inBytes.length]; for (int i = 0; i < inBytes.length; i++) { maskedBytes[i] = (byte)(inBytes[i] & mask[i % inBytes.length]); } return maskedBytes; } */ private void invokeChangeListeners(PortInfoTreeMap oldInfo, PortInfoTreeMap newInfo) { // just call the processPortInfoChange method of each listener for (int i = 0; i < changeListeners.size(); i++) { ((PortInfoChangeListener)changeListeners.elementAt(i)).processPortInfoChange(oldInfo, newInfo); } } public void run() { while(!Thread.currentThread().isInterrupted()) { try { // retrieve current info from base station PortInfoTreeMap newInfo = getInfo(); messagesArea.setText("Information retrieved " + (new Date()).toString() + ".\n"); // now refresh display refreshInfoDisplay(newInfo); // see if info has changed; if so, take action invokeChangeListeners(currentInfo, newInfo); currentInfo = newInfo; } catch(IllegalArgumentException ex) { // thrown by PortInfoTreeMap constructor if no data retrieved messagesArea.setText("Error retrieving information (check password)\n"); } catch(SocketException e) { messagesArea.setText("Error retrieving information: " + e + "\n"); } catch(IOException e) { messagesArea.setText("Error retrieving information: timed out waiting for response.\n"); } catch (Exception e) { messagesArea.setText("Error retrieving information: " + e.getMessage() + "\n"); } try { // sleep for inspection interval seconds Thread.currentThread().sleep(1000 * preferences.queryInterval); } catch(InterruptedException e) { // don't bother informing of interruption Thread.currentThread().interrupt(); } } } private void saveSettings() { // save into file PortInspector.ini ObjectOutputStream outStream; try { outStream = new ObjectOutputStream(new FileOutputStream("PortInspector.ini")); outStream.writeObject(preferences); outStream.close(); preferencesSaved = true; } catch (Exception e) { // oh well... messagesArea.setText("Couldn't write settings: " + e.toString()); preferencesSaved = false; } } private void readSettings() { // read from file PortInspector.ini try { ObjectInputStream inStream = new ObjectInputStream(new FileInputStream("PortInspector.ini")); preferences = (Preferences)inStream.readObject(); inStream.close(); preferencesSaved = true; } catch (Exception e) { // couldn't read; just return empty settings //messagesArea.setText("Couldn't read settings: " + e.toString()); preferences = new Preferences(); preferencesSaved = false; } } public static void main(String args[]) { try { PortInspector theApp = new PortInspector(); } catch (Exception e) {} } }portinspector-1.0/AirportDiscoverer.java0000644000175000017500000001725007614603612020146 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 java.awt.event.*; import java.io.*; import javax.swing.*; /** * Broadcasts discovery packet, waits for responses. Displays responding devices' IP addresses, * names, and device-type identifying strings. */ public class AirportDiscoverer extends JFrame implements ActionListener, Runnable { JButton stopDiscoveryButton, closeButton; JTextArea theArea; Thread discoveryThread; public AirportDiscoverer() { setUpDisplay(); this.pack(); this.show(); discoveryThread = new Thread(this); discoveryThread.start(); } private void setUpDisplay() { this.setTitle("Base Station Discovery"); stopDiscoveryButton = new JButton("Stop Discovery"); stopDiscoveryButton.setActionCommand("stop discovery"); stopDiscoveryButton.addActionListener(this); closeButton = new JButton("Close"); closeButton.setActionCommand("close"); closeButton.addActionListener(this); theArea = new JTextArea(20,70); theArea.setLineWrap(true); theArea.setFont(new Font("Monospaced", Font.PLAIN, 10)); JScrollPane messagesScroll = new JScrollPane(theArea); // 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; Insets theMargin = new Insets(2,2,2,2); c.insets = theMargin; c.anchor = GridBagConstraints.CENTER; c.weightx = .5; c.weighty = .5; JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(stopDiscoveryButton, c); buttonPanel.add(stopDiscoveryButton); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(closeButton, c); buttonPanel.add(closeButton); this.getContentPane().setLayout(new BorderLayout(5,5)); this.getContentPane().add("North", buttonPanel); this.getContentPane().add("Center", messagesScroll); } public void actionPerformed(ActionEvent theEvent) // respond to button pushes, menu selections { String command = theEvent.getActionCommand(); try { if (command == "close") { discoveryThread.interrupt(); this.hide(); this.dispose(); } if (command == "stop discovery") { discoveryThread.interrupt(); } } catch (Exception e) { } } public void run() { try { DatagramSocket dSocket = new DatagramSocket(); dSocket.setSoTimeout(1000); //1 second int AIRPORT_PORT = 192; InetAddress broadcastAddress = InetAddress.getByName("255.255.255.255"); byte[] bytes = new byte[116]; // from sniffs bytes[0] = (byte)0x01; DatagramPacket outPacket = new DatagramPacket(bytes, bytes.length, broadcastAddress, AIRPORT_PORT); dSocket.send(outPacket); while(! discoveryThread.interrupted()) { //bytes = new byte[116]; // from sniffs DatagramPacket inPacket = new DatagramPacket(bytes, bytes.length); try { dSocket.receive(inPacket); bytes = inPacket.getData(); String sourceAddress = inPacket.getAddress().getHostAddress(); // parse info in response packet /* System.out.println("Returned Message bytes:"); for (int i = 0; i < bytes.length; ++i) System.out.print(hexByte(bytes[i]) + " "); */ AirportDiscoveryInfo theInfo = new AirportDiscoveryInfo(bytes); long upTime = Long.parseLong(theInfo.get("Base station uptime").toString()); upTime = upTime / 100; // put into seconds // change to days:hours:minutes format long days = upTime / (3600 * 24); long hours = (upTime / 3600) % 24; long minutes = (upTime / 60) % 60; long seconds = upTime % 60; String dayString = new String(); dayString += days; String hourString = new String(); hourString += hours; if (hourString.length() < 2) hourString = "0" + hourString; // make hours, minutes and seconds have 2 digits String minuteString = new String(); minuteString += minutes; if (minuteString.length() < 2) minuteString = "0" + minuteString; String secondString = new String(); secondString += seconds; if (secondString.length() < 2) secondString = "0" + secondString; String timeString = dayString + ":" + hourString + ":" + minuteString; theArea.append("Access point found:\n"); theArea.append(" Local LAN IP address: " + theInfo.get("Base station IP address").toString() + "\n"); theArea.append(" External IP address: " + sourceAddress + "\n"); theArea.append(" MAC address: " + theInfo.get("Base station Mac address").toString() + "\n"); theArea.append(" Device name: " + theInfo.get("System name").toString() + "\n"); theArea.append(" Device type: " + theInfo.get("Device identifying string").toString() + "\n"); theArea.append(" Uptime (days:hrs:mins): " + timeString + "\n"); /* // now send out some SNMP requests to retrieve additional info from // the responding station; would really like to ARP on the MAC address // in case the returned IP address is unhappy (e.g., 0.0.0.0).... try { String community = "public"; int version = 0; // SNMPv1 InetAddress hostAddress = InetAddress.getByName(theInfo.get("waIP").toString()); SNMPv1CommunicationInterface comInterface = new SNMPv1CommunicationInterface(version, hostAddress, community); String itemID = ""; SNMPVarBindList newVars = comInterface.getMIBEntry(itemID); SNMPSequence pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); SNMPObject snmpValue = pair.getSNMPObjectAt(1); theArea.append("External IP adress: " + snmpValue.toString() + "\n"); } catch(Exception e) { // do nothing; problem getting SNMP stuff... } */ theArea.append("\n"); } catch (InterruptedIOException e) { // will get here if nothing received in 1 second; used to check if interrupted // by user! } } } catch(Exception e) { theArea.append("Exception during discovery: " + e + "\n"); } theArea.append("Discovery finished.\n"); } 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; } }portinspector-1.0/AUTHORS0000644000175000017500000000036707614611342014705 0ustar julienjulienAirPort Port Inspector http://gicl.mcs.drexel.edu/sevy/airport Jon Sevy Geometric and Intelligent Computing Laboratory Department of Mathematics and Computer Science Drexel University http://gicl.mcs.drexel.edu/sevy portinspector-1.0/PreferencesDialog.java0000644000175000017500000001110007614606547020057 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.awt.event.*; import java.io.*; public class PreferencesDialog extends JDialog implements ActionListener { JTextField ipAddressField = new JTextField(10); JPasswordField passwordField = new JPasswordField(10); JTextField intervalField = new JTextField(10); JLabel ipAddressLabel = new JLabel("Base station address:"); JLabel passwordLabel = new JLabel("Base station password:"); JLabel intervalLabel = new JLabel("Base station query interval (seconds):"); JButton okButton, cancelButton; boolean cancelled = false; Preferences newPrefs; public PreferencesDialog(Frame owner, Preferences currentPreferences) { // create as modal dialog super(owner, "Preferences", true); // set new prefs to current newPrefs = currentPreferences; ipAddressField.setText(currentPreferences.ipAddress); passwordField.setText(""); intervalField.setText("" + currentPreferences.queryInterval); okButton = new JButton("OK"); okButton.setActionCommand("ok"); okButton.addActionListener(this); this.getRootPane().setDefaultButton(okButton); cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(this); // 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; Insets theMargin = new Insets(2,2,2,2); c.insets = theMargin; c.anchor = GridBagConstraints.CENTER; c.weightx = .5; c.weighty = .5; this.getContentPane().setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(ipAddressLabel, c); this.getContentPane().add(ipAddressLabel); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(ipAddressField, c); this.getContentPane().add(ipAddressField); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(passwordLabel, c); this.getContentPane().add(passwordLabel); c.gridx = 2; c.gridy = 2; theLayout.setConstraints(passwordField, c); this.getContentPane().add(passwordField); c.gridx = 1; c.gridy = 3; theLayout.setConstraints(okButton, c); this.getContentPane().add(okButton); c.gridx = 2; c.gridy = 3; theLayout.setConstraints(cancelButton, c); this.getContentPane().add(cancelButton); this.pack(); this.show(); } public void actionPerformed(ActionEvent theEvent) // respond to button pushes, menu selections { String command = theEvent.getActionCommand(); if (command.equals("ok")) { if (validateNewPreferences()) this.hide(); } if (command == "cancel") { cancelled = true; this.hide(); } } private boolean validateNewPreferences() { int interval; // check the interval parameter try { interval = Integer.parseInt(intervalField.getText()); if (interval <= 0) throw new NumberFormatException(); newPrefs = new Preferences(); newPrefs.ipAddress = ipAddressField.getText(); newPrefs.password = passwordField.getText(); newPrefs.queryInterval = interval; return true; } catch(NumberFormatException e) { JOptionPane.showMessageDialog(this, "Value supplied must be a positive integer."); return false; } } public Preferences getPreferences() { return newPrefs; } public boolean isCancelled() { return cancelled; } }portinspector-1.0/Preferences.java0000644000175000017500000000325307614604020016731 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.io.*; import java.net.*; public class Preferences implements Serializable { public String ipAddress; public String password; public int queryInterval; public int displayType; public Preferences() { ipAddress = ""; password = ""; queryInterval = 5; displayType = PortMapTable.DETAILED; } public boolean equals(Object otherPrefsObject) { Preferences otherPrefs = (Preferences)otherPrefsObject; // compare all fields but passwords if ( (this.ipAddress.equals(otherPrefs.ipAddress)) && (this.queryInterval == otherPrefs.queryInterval) && (this.displayType == otherPrefs.displayType) ) { return true; } else { return false; } } }portinspector-1.0/AirportDiscoveryInfo.java0000644000175000017500000000726307614603640020630 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.*; /** * Collects together information about the location of pieces of information * in the 116-byte Discovery memory block, and creates appropriate AirportInfoRecords * (with ByteBlockWindows into the underlying ByteBlock) to read and write * the information. */ public class AirportDiscoveryInfo extends Hashtable { /** * Create new */ public AirportDiscoveryInfo(byte[] baseBlock) { int baseStartIndex; int maxSize; int dataType; int encryption; byte[] bytes; String name; /** * Base station MAC address */ baseStartIndex = 0x024; maxSize = 6; bytes = new byte[maxSize]; for (int i = 0; i < maxSize; i++) bytes[i] = baseBlock[baseStartIndex + i]; encryption = AirportInfoRecord.UNENCRYPTED; dataType = AirportInfoRecord.BYTE_STRING; name = "Base station Mac address"; this.put(name, new AirportInfoRecord(name, name, dataType, encryption, maxSize, bytes)); /** * Base station IP address: byte 2*16 + 13 */ baseStartIndex = 0x02C; maxSize = 4; bytes = new byte[maxSize]; for (int i = 0; i < maxSize; i++) bytes[i] = baseBlock[baseStartIndex + i]; encryption = AirportInfoRecord.UNENCRYPTED; dataType = AirportInfoRecord.IP_ADDRESS; name = "Base station IP address"; this.put(name, new AirportInfoRecord(name, name, dataType, encryption, maxSize, bytes)); /** * Base station name: byte 3*16 + 1 */ baseStartIndex = 0x030; maxSize = 32; bytes = new byte[maxSize]; for (int i = 0; i < maxSize; i++) bytes[i] = baseBlock[baseStartIndex + i]; encryption = AirportInfoRecord.UNENCRYPTED; dataType = AirportInfoRecord.CHAR_STRING; name = "System name"; this.put(name, new AirportInfoRecord(name, name, dataType, encryption, maxSize, bytes)); /** * Base station uptime: byte 5*16 + 1 */ baseStartIndex = 0x050; maxSize = 4; bytes = new byte[maxSize]; for (int i = 0; i < maxSize; i++) bytes[i] = baseBlock[baseStartIndex + i]; encryption = AirportInfoRecord.UNENCRYPTED; dataType = AirportInfoRecord.UNSIGNED_INTEGER; name = "Base station uptime"; this.put(name, new AirportInfoRecord(name, name, dataType, encryption, maxSize, bytes)); /** * Device identifying string: byte 5*16 + 5 */ baseStartIndex = 0x054; maxSize = 32; bytes = new byte[maxSize]; for (int i = 0; i < maxSize; i++) bytes[i] = baseBlock[baseStartIndex + i]; encryption = AirportInfoRecord.UNENCRYPTED; dataType = AirportInfoRecord.CHAR_STRING; name = "Device identifying string"; this.put(name, new AirportInfoRecord(name, name, dataType, encryption, maxSize, bytes)); } public AirportInfoRecord get(String name) { return (AirportInfoRecord)super.get(name); } }portinspector-1.0/AirportInfoRecord.java0000644000175000017500000003712307614603652020100 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.math.*; import java.util.*; import java.io.*; /** * This class defines a structure to hold information about the location and format (type) * of a piece of information in the Airport memory block. Location is specified by a triple: * the object identifier number (1 to 68), row in the block (0 to 15), and column (0 to 15), * where the ByteBlockWindow begins; size of the window is specified by giving the number of * rows and columns in the window; and the datatype is specified as one of the class's constants. * * The class also implements a toString() method which provides a pretty-printed representation * of the value in the window based on its datatype, and a setBytesFromString() method which * writes a value to the window given an appropriately formatted String representation. */ public class AirportInfoRecord { public static final int CHAR_STRING = 0; public static final int IP_ADDRESS = 1; public static final int BYTE_STRING = 2; public static final int PHONE_NUMBER = 3; public static final int UNSIGNED_INTEGER = 4; public static final int BYTE = 5; public static final int LITTLE_ENDIAN_UNSIGNED_INTEGER = 6; public static final int UNENCRYPTED = 0; public static final int ENCRYPTED = 2; public String tag; public String description; public int dataType; public int encryption; public int maxLength; public byte[] value; public static byte[] cipherBytes = { (byte)0x0e, (byte)0x39, (byte)0xf8, (byte)0x05, (byte)0xc4, (byte)0x01, (byte)0x55, (byte)0x4f, (byte)0x0c, (byte)0xac, (byte)0x85, (byte)0x7d, (byte)0x86, (byte)0x8a, (byte)0xb5, (byte)0x17, (byte)0x3e, (byte)0x09, (byte)0xc8, (byte)0x35, (byte)0xf4, (byte)0x31, (byte)0x65, (byte)0x7f, (byte)0x3c, (byte)0x9c, (byte)0xb5, (byte)0x6d, (byte)0x96, (byte)0x9a, (byte)0xa5, (byte)0x07, (byte)0x2e, (byte)0x19, (byte)0xd8, (byte)0x25, (byte)0xe4, (byte)0x21, (byte)0x75, (byte)0x6f, (byte)0x2c, (byte)0x8c, (byte)0xa5, (byte)0x9d, (byte)0x66, (byte)0x6a, (byte)0x55, (byte)0xf7, (byte)0xde, (byte)0xe9, (byte)0x28, (byte)0xd5, (byte)0x14, (byte)0xd1, (byte)0x85, (byte)0x9f, (byte)0xdc, (byte)0x7c, (byte)0x55, (byte)0x8d, (byte)0x76, (byte)0x7a, (byte)0x45, (byte)0xe7, (byte)0xce, (byte)0xf9, (byte)0x38, (byte)0xc5, (byte)0x04, (byte)0xc1, (byte)0x95, (byte)0x8f, (byte)0xcc, (byte)0x6c, (byte)0x45, (byte)0xbd, (byte)0x46, (byte)0x4a, (byte)0x75, (byte)0xd7, (byte)0xfe, (byte)0xc9, (byte)0x08, (byte)0xf5, (byte)0x34, (byte)0xf1, (byte)0xa5, (byte)0xbf, (byte)0xfc, (byte)0x5c, (byte)0x75, (byte)0xad, (byte)0x56, (byte)0x5a, (byte)0x65, (byte)0xc7, (byte)0xee, (byte)0xd9, (byte)0x18, (byte)0xe5, (byte)0x24, (byte)0xe1, (byte)0xb5, (byte)0xaf, (byte)0xec, (byte)0x4c, (byte)0x65, (byte)0xdd, (byte)0x26, (byte)0x2a, (byte)0x15, (byte)0xb7, (byte)0x9e, (byte)0xa9, (byte)0x68, (byte)0x95, (byte)0x54, (byte)0x91, (byte)0xc5, (byte)0xdf, (byte)0x9c, (byte)0x3c, (byte)0x15, (byte)0xcd, (byte)0x36, (byte)0x3a, (byte)0x05, (byte)0xa7, (byte)0x8e, (byte)0xb9, (byte)0x78, (byte)0x85, (byte)0x44, (byte)0x81, (byte)0xd5, (byte)0xcf, (byte)0x8c, (byte)0x2c, (byte)0x05, (byte)0xfd, (byte)0x06, (byte)0x0a, (byte)0x35, (byte)0x97, (byte)0xbe, (byte)0x89, (byte)0x48, (byte)0xb5, (byte)0x74, (byte)0xb1, (byte)0xe5, (byte)0xff, (byte)0xbc, (byte)0x1c, (byte)0x35, (byte)0xed, (byte)0x16, (byte)0x1a, (byte)0x25, (byte)0x87, (byte)0xae, (byte)0x99, (byte)0x58, (byte)0xa5, (byte)0x64, (byte)0xa1, (byte)0xf5, (byte)0xef, (byte)0xac, (byte)0x0c, (byte)0x25, (byte)0x1d, (byte)0xe6, (byte)0xea, (byte)0xd5, (byte)0x77, (byte)0x5e, (byte)0x69, (byte)0xa8, (byte)0x55, (byte)0x94, (byte)0x51, (byte)0x05, (byte)0x1f, (byte)0x5c, (byte)0xfc, (byte)0xd5, (byte)0x0d, (byte)0xf6, (byte)0xfa, (byte)0xc5, (byte)0x67, (byte)0x4e, (byte)0x79, (byte)0xb8, (byte)0x45, (byte)0x84, (byte)0x41, (byte)0x15, (byte)0x0f, (byte)0x4c, (byte)0xec, (byte)0xc5, (byte)0x3d, (byte)0xc6, (byte)0xca, (byte)0xf5, (byte)0x57, (byte)0x7e, (byte)0x49, (byte)0x88, (byte)0x75, (byte)0xb4, (byte)0x71, (byte)0x25, (byte)0x3f, (byte)0x7c, (byte)0xdc, (byte)0xf5, (byte)0x2d, (byte)0xd6, (byte)0xda, (byte)0xe5, (byte)0x47, (byte)0x6e, (byte)0x59, (byte)0x98, (byte)0x65, (byte)0xa4, (byte)0x61, (byte)0x35, (byte)0x2f, (byte)0x6c, (byte)0xcc, (byte)0xe5, (byte)0x5d, (byte)0xa6, (byte)0xaa, (byte)0x95, (byte)0x37, (byte)0x1e, (byte)0x29, (byte)0xe8, (byte)0x15, (byte)0xd4, (byte)0x11, (byte)0x45, (byte)0x5f, (byte)0x1c, (byte)0xbc, (byte)0x95, (byte)0x4d, (byte)0xb6, (byte)0xba, (byte)0x85, (byte)0x27 }; /** * Create a new record with the specified parameters */ public AirportInfoRecord(String tag, String description, int dataType, int encryption, int maxLength, byte[] value) { this.tag = tag; this.description = description; this.dataType = dataType; this.encryption = encryption; this.maxLength = maxLength; this.value = value; } public AirportInfoRecord(String tag, String description, int dataType, int encryption, int maxLength) { this.tag = tag; this.description = description; this.maxLength = maxLength; this.dataType = dataType; this.encryption = encryption; this.value = new byte[maxLength]; } public AirportInfoRecord() { this.tag = ""; this.description = ""; this.dataType = CHAR_STRING; this.encryption = UNENCRYPTED; this.maxLength = 0; this.value = new byte[0]; } /** * Clear all bytes in the underlying ByteBlockWindow. */ public void clearWindow() { this.value = new byte[0]; } /** * Method which provides a pretty-printed representation of the value bytes * based on its datatype. */ public String toString() { String returnString = new String(); byte[] bytes = value; switch (dataType) { case UNSIGNED_INTEGER: { try { returnString = convertToUnsignedInteger(bytes); } catch (NumberFormatException e) { returnString = hexBytes(bytes); } break; } case LITTLE_ENDIAN_UNSIGNED_INTEGER: { try { bytes = reverseBytes(bytes); returnString = convertToUnsignedInteger(bytes); } catch (NumberFormatException e) { returnString = hexBytes(bytes); } break; } case CHAR_STRING: case PHONE_NUMBER: { returnString = convertToCharString(bytes); break; } case IP_ADDRESS: { returnString = convertToIPAddress(bytes); break; } case BYTE: case BYTE_STRING: default: { returnString = hexBytes(bytes); break; } } return returnString; } private String convertToCharString(byte[] bytes) { String charString; if (bytes.length == 0) { charString = ""; } else { charString = new String(bytes); // trim 0's int endIndex = charString.indexOf('\0'); if (endIndex >= 0) charString = charString.substring(0, endIndex); } return charString; } private String convertToUnsignedInteger(byte[] bytes) { BigInteger bigInt = new BigInteger(1, bytes); return bigInt.toString(); } private String convertToIPAddress(byte[] bytes) { String returnString = new String(); int value; for (int i = 0; i < bytes.length - 1; i++) { value = bytes[i]; if (value < 0) value += 256; returnString += value + "."; } value = bytes[bytes.length - 1]; if (value < 0) value += 256; returnString += value; return returnString; } /** * Writes value bytes given an appropriately formatted String representation for * the value. */ public void setBytesFromString(String valueString) throws ValueFormatException { byte[] bytes; switch (dataType) { case UNSIGNED_INTEGER: { bytes = convertFromUnsignedInteger(valueString); break; } case LITTLE_ENDIAN_UNSIGNED_INTEGER: { bytes = convertFromUnsignedInteger(valueString); bytes = reverseBytes(bytes); break; } case CHAR_STRING: case PHONE_NUMBER: { if (valueString.length() > maxLength - 1) { // System.out.println("Value format exception at " + OIDNum + " " + OIDRow + " " + OIDCol); throw new ValueFormatException("Maximum " + (maxLength - 1) + " characters."); } else bytes = valueString.getBytes(); break; } case IP_ADDRESS: { bytes = convertFromIPv4Address(valueString); break; } case BYTE: case BYTE_STRING: default: { bytes = convertFromHexString(valueString); break; } } this.value = bytes; } private byte[] convertFromIPv4Address(String addressString) throws ValueFormatException { // might be partial address byte[] bytes = new byte[maxLength]; int i = 0; int value; StringTokenizer st = new StringTokenizer(addressString, "."); if (st.countTokens() != maxLength) { if (st.countTokens() == 4) throw new ValueFormatException("Bad IP address: must be of form a.b.c.d, with a,b,c and d between 0 and 255."); else throw new ValueFormatException("Bad dotted address supplied: should have " + maxLength + " components."); } while (st.hasMoreTokens()) { try { String component = st.nextToken(); value = Integer.parseInt(component); if ((value < 0) || (value > 255)) throw new ValueFormatException("Bad IP address: must be of form a.b.c.d, with a,b,c and d between 0 and 255."); else { bytes[i] = (byte)value; i++; } } catch (NumberFormatException e) { throw new ValueFormatException("Bad IP address: must be of form a.b.c.d, with a,b,c and d between 0 and 255."); } } return bytes; } private byte[] convertFromUnsignedInteger(String valueString) throws ValueFormatException { int length = maxLength; byte[] bytes = new byte[length]; try { int minValue = 0; long maxValue = 1; for (int i = 0; i < length; i++) { maxValue *= 256; } maxValue -= 1; long value = Long.parseLong(valueString); if ((value < minValue) || (value > maxValue)) throw new ValueFormatException("Value must be between " + minValue + " and " + maxValue + "."); for (int i = 0; i < length; i++) { bytes[length - i - 1] = (byte)(value%256); value = value/256; } } catch (NumberFormatException e) { throw new ValueFormatException("Bad number format."); } return bytes; } private byte[] convertFromHexString(String hexString) throws ValueFormatException { byte[] bytes = new byte[this.maxLength]; // eliminate spaces in string hexString.trim(); int index; while((index = hexString.indexOf(' ')) != -1) { hexString = hexString.substring(0,index) + hexString.substring(index+1); } // make sure have even number of hex digits if (2 * (hexString.length()/2) != hexString.length()) throw new ValueFormatException("Must have an even number of hexadecimal digits."); // make sure don't have wrong number of bytes if ((this.maxLength > 0) && (hexString.length() / 2 != maxLength)) throw new ValueFormatException("Too many hexadecimal digits (must have " + 2*maxLength + " hex digits)."); for (int i = 0; i < (hexString.length()/2); i++) { // get next pair of digits String digitString = hexString.substring(2*i,2*i+2); try { int value = Integer.parseInt(digitString, 16); bytes[i] = (byte)value; } catch (NumberFormatException e) { throw new ValueFormatException("Entries must be hexadecimal digits (0 through 9 and a through f or A through F) or spaces."); } } return bytes; } private byte[] reverseBytes(byte[] inBytes) { int length = inBytes.length; byte[] outBytes = new byte[length]; for (int i = 0; i < length; i++) { outBytes[i] = inBytes[length - i - 1]; } return outBytes; } public byte[] getValue() { return value; } public void setValue(byte[] bytes) { // just set value array value = bytes; } public byte[] getUpdateBytes() { // serialize all the fields ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream outStream = new DataOutputStream(byteStream); try { outStream.writeBytes(tag); outStream.writeInt(encryption); outStream.writeInt(value.length); if (value.length > 0) { // encrypt bytes if needed if (this.encryption == ENCRYPTED) { outStream.write(encryptBytes(cipherBytes, value)); } else { outStream.write(value); } } } catch(IOException e) { // IOException should never occur... } return byteStream.toByteArray(); } public byte[] getRequestBytes() { // serialize all the fields ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128); DataOutputStream outStream = new DataOutputStream(byteStream); try { outStream.writeBytes(tag); outStream.writeInt(encryption); outStream.writeInt(0); } catch(IOException e) { // IOException should never occur... } return byteStream.toByteArray(); } public static byte[] decryptBytes(byte[] cipherString, byte[] encryptedString) { byte[] returnBytes = new byte[encryptedString.length]; // just xor each byte in encryptedString with cipherString int length = encryptedString.length; for (int i = 0; i < length; i++) { returnBytes[i] = (byte)(encryptedString[i] ^ cipherString[i%256]); } return returnBytes; } public static byte[] encryptBytes(byte[] cipherString, byte[] encryptedString) { return decryptBytes(cipherString, encryptedString); } private int getIntegerValue(byte[] valueBytes) { int value = 0; for (int i = 0; i < valueBytes.length; i++) { int absValue = valueBytes[i]; if (absValue < 0) absValue += 256; value = value*256 + absValue; } return value; } 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; } private String hexBytes(byte[] bytes) { String returnString = new String(); for(int i = 0; i < bytes.length; i++) { returnString += hexByte(bytes[i]); } return returnString; } }portinspector-1.0/PortInfoChangeListener.java0000644000175000017500000000177207614603714021061 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 * */ public interface PortInfoChangeListener { // do whatever in response to a change in the retrieved info public void processPortInfoChange(PortInfoTreeMap oldInfo, PortInfoTreeMap newInfo); }portinspector-1.0/PortInfo.java0000644000175000017500000000374707614603705016251 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 * */ public class PortInfo { public String localIP; public int localPort; public String localMAC; public String remoteIP; public int remotePort; public String gatewayIP; public int gatewayPort; public int portType; public int lifetime; public PortInfo(String localIP, int localPort, String localMAC, String remoteIP, int remotePort, String gatewayIP, int gatewayPort, int portType, int lifetime) { this.localIP = localIP; this.localPort = localPort; this.localMAC = localMAC; this.remoteIP = remoteIP; this.remotePort = remotePort; this.gatewayIP = gatewayIP; this.gatewayPort = gatewayPort; this.portType = portType; this.lifetime = lifetime; } public PortInfo() { this("", 0, "", "", 0, "", 0, 0, 0); } public String toString() { String returnValue = new String(); returnValue += localIP + " : " + localPort + " : " + localMAC + " : " + remoteIP + " : " + remotePort + " : " + gatewayIP + " : " + gatewayPort + " : " + portType + " : " + lifetime; return returnValue; } }portinspector-1.0/ValueFormatException.java0000644000175000017500000000224307614603622020601 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 * */ /** * Used to report incorrect value format messages, when inappropriate string has been supplied * in a textfield. */ public class ValueFormatException extends Exception { /** * Construct new exception with specified error message. */ public ValueFormatException(String specifics) { super(specifics); } }portinspector-1.0/PortMapTable.java0000644000175000017500000002003307614603757017035 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 java.awt.event.*; import java.util.*; import java.io.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; /** * Handles display and updating of port mapping information. */ public class PortMapTable extends JPanel { private Vector portInfoVector, portCountVector; private JTable table; private AbstractTableModel tableModel; private JScrollPane scrollPane; private int displayType; public static final int DETAILED = 0; public static final int SIMPLE = 1; /** * Table model which maintains detailed list of port mappings. */ private class DetailedPortMapTableModel extends AbstractTableModel { public int getColumnCount() { return 8; } public int getRowCount() { return portInfoVector.size(); } public boolean isCellEditable(int row, int col) { return false; } public String getColumnName(int col) { switch (col) { case 0: return " Local MAC "; case 1: return " Local IP "; case 2: return "Local port"; case 3: return " Remote IP "; case 4: return "Remote port"; case 5: return "Router port"; case 6: return "Port type"; case 7: return "Life (sec)"; default: return ""; } } public Object getValueAt(int row, int col) { if (row < portInfoVector.size()) { PortInfo portInfo = (PortInfo)portInfoVector.elementAt(row); switch (col) { case 0: return portInfo.localMAC; case 1: return portInfo.localIP; case 2: return new Integer(portInfo.localPort); case 3: return portInfo.remoteIP; case 4: return new Integer(portInfo.remotePort); case 5: return new Integer(portInfo.gatewayPort); case 6: { if (portInfo.portType == 1) return "TCP"; else return "UDP"; } case 7: return new Integer(portInfo.lifetime); default: return ""; } } else return ""; } } /** * Table model which maintains simplified list of port mappings. */ private class SimplePortMapTableModel extends AbstractTableModel { public int getColumnCount() { return 3; } public int getRowCount() { return portCountVector.size(); } public boolean isCellEditable(int row, int col) { return false; } public String getColumnName(int col) { switch (col) { case 0: return "Local MAC address"; case 1: return "Local IP address"; case 2: return "Open ports"; default: return ""; } } public Object getValueAt(int row, int col) { if (row < portCountVector.size()) { PortCount portCount = (PortCount)portCountVector.elementAt(row); switch (col) { case 0: return portCount.localMAC; case 1: return portCount.localIP; case 2: return new Integer(portCount.portCount); default: return ""; } } else return ""; } public void setValueAt(Object newValue, int row, int col) { } } /** * Create new table based on data in airportInfo. */ public PortMapTable(PortInfoTreeMap portInfoHashtable, int displayType) { this.portInfoVector = new Vector(portInfoHashtable.values()); setPortCount(); table = new JTable(); setDisplayType(displayType); scrollPane = new JScrollPane(table); setUpDisplay(); } private void setUpDisplay() { GridBagLayout theLayout = new GridBagLayout(); this.setLayout(theLayout); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.fill = GridBagConstraints.BOTH; c.ipadx = 0; c.ipady = 0; Insets theMargin = new Insets(2,2,2,2); c.insets = theMargin; c.anchor = GridBagConstraints.CENTER; c.weightx = .5; c.weighty = .5; c.gridx = 1; c.gridy = 1; theLayout.setConstraints(scrollPane, c); this.add(scrollPane); } public synchronized void setInfo(PortInfoTreeMap portInfoHashtable) { this.portInfoVector = new Vector(portInfoHashtable.values()); setPortCount(); tableModel.fireTableDataChanged(); //table.doLayout(); //table.repaint(); //this.revalidate(); } public synchronized void setDisplayType(int displayType) { this.displayType = displayType; if (displayType == DETAILED) { tableModel = new DetailedPortMapTableModel(); table.setModel(tableModel); table.setPreferredScrollableViewportSize(new Dimension(680,300)); } else // (displayType == SIMPLE) { tableModel = new SimplePortMapTableModel(); table.setModel(tableModel); table.setPreferredScrollableViewportSize(new Dimension(300,300)); } setColumnPreferredWidths(table); table.setCellSelectionEnabled(false); } /** * Refresh the display based on the current data in the underlying byte block. */ /* public synchronized void refreshDisplay() { } */ private void setPortCount() { portCountVector = new Vector(); String currentIP = ""; PortCount portCount = new PortCount(currentIP, ""); for (int i = 0; i < portInfoVector.size(); i++) { PortInfo portInfo = (PortInfo)portInfoVector.elementAt(i); if (currentIP.equals(portInfo.localIP)) { // same local host as previous; just increment count portCount.portCount++; } else { // new local host; add new entry portCount = new PortCount(portInfo.localIP, portInfo.localMAC); portCount.portCount++; portCountVector.add(portCount); currentIP = portInfo.localIP; } } } public void setColumnPreferredWidths(JTable table) { TableModel tableModel = table.getModel(); TableColumnModel tableColumnModel = table.getColumnModel(); for (int i = 0; i < tableModel.getColumnCount(); i++) { int stringSize = tableModel.getColumnName(i).length(); tableColumnModel.getColumn(i).setPreferredWidth(stringSize*20); } } /* public void doLayout() { super.doLayout(); System.out.println("doLayout called"); } public void validate() { super.validate(); System.out.println("validate called"); } public void invalidate() { super.invalidate(); System.out.println("invalidate called"); } public void repaint() { super.repaint(); System.out.println("repaint called"); } public void update(Graphics g) { super.update(g); System.out.println("update called, clipRect = " + g.getClipBounds()); } public void paintAll(Graphics g) { super.paintAll(g); System.out.println("paintall called"); } public void paint(Graphics g) { super.paint(g); //System.out.println("paint called"); System.out.println("paint called, mapcount = " + portInfoVector.size() + ", table = " + table); } */ }portinspector-1.0/PortCount.java0000644000175000017500000000276107614603676016450 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 * */ public class PortCount { public String localIP; public String localMAC; public int portCount; public PortCount(String localIP, String localMAC, int portCount) { this.localIP = localIP; this.localMAC = localMAC; this.portCount = portCount; } public PortCount() { this("", "", 0); } public PortCount(String localIP, String localMAC) { this(localIP, localMAC, 0); } public String toString() { String returnValue = new String(); returnValue += localIP + " : " + localMAC + " : " + portCount; return returnValue; } }portinspector-1.0/ArpInfo.java0000644000175000017500000000245707614603660016044 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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 * */ public class ArpInfo { public String ipAddress; public String macAddress; public ArpInfo(String ipAddress, String macAddress) { this.ipAddress = ipAddress; this.macAddress = macAddress; } public ArpInfo() { this("", ""); } public String toString() { String returnValue = new String(); returnValue += ipAddress + " : " + macAddress; return returnValue; } }portinspector-1.0/ArpInfoTreeMap.java0000644000175000017500000001121207614603667017316 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.math.*; import snmp.*; public class ArpInfoTreeMap extends TreeMap { public ArpInfoTreeMap() { // create empty Hashtable super(); } public ArpInfoTreeMap(SNMPVarBindList varBindList) { // create and populate Hashtable of ArpInfo objects super(); // make list of MAC address / IP address pairs if (varBindList.size() > 0) { int i = 0; SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); String oid = snmpOID.toString(); String oidBase = "1.3.6.1.2.1.4.22.1.1"; while(oid.startsWith(oidBase)) { // use just to get index - note that it's the interface index followed by the IP address; // SO, we strip off the interface, and VOILA, we have the table hashed by IP. String tableIndex = oid.substring(oidBase.length() + 1 + 2); // extra 2 strips off the interface index and dot // add a new ARPInfo object to hashtable, hashed by index this.put(tableIndex, new ArpInfo()); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } // get MAC addresses oidBase = "1.3.6.1.2.1.4.22.1.2"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1 + 2); // extra 2 strips off the interface index and dot // modify ARPInfo in hashtable ArpInfo arpInfo = (ArpInfo)this.get(tableIndex); SNMPOctetString macAddress = (SNMPOctetString)variablePair.getSNMPObjectAt(1); arpInfo.macAddress = macAddress.toHexString(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } // get IP addresses oidBase = "1.3.6.1.2.1.4.22.1.3"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1 + 2); // extra 2 strips off the interface index and dot // modify ARPInfo in hashtable ArpInfo arpInfo = (ArpInfo)this.get(tableIndex); SNMPIPAddress ipAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); arpInfo.ipAddress = ipAddress.toString(); i++; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } } } public String toString() { String returnValue = new String(); Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { ArpInfo arpInfo = (ArpInfo)iterator.next(); returnValue += arpInfo.toString() + "\n"; } return returnValue; } }portinspector-1.0/PortInfoTreeMap.java0000644000175000017500000002600707614603721017517 0ustar julienjulien/* * AirPort Port Inspector * * Copyright (C) 2003, 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.math.*; import snmp.*; public class PortInfoTreeMap extends TreeMap { public PortInfoTreeMap() { // create empty Hashtable super(); } public PortInfoTreeMap(SNMPVarBindList varBindList) { // create and populate Hashtable of PortInfo objects super(); // get all OIDs for base OID 1.3.6.1.4.1.731.100.3.1.1.1; // index consists of 1.3.6.1.4.1.731.100.3.1.1.1...., if (varBindList.size() > 0) { int i = 0; SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); String oid = snmpOID.toString(); String oidBase = "1.3.6.1.4.1.731.100.3.1.1.1"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // add a new PortInfo object to hashtable, hashed by index this.put(tableIndex, new PortInfo()); // this entry also gives port type (TCP or UDP) PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPInteger port = (SNMPInteger)variablePair.getSNMPObjectAt(1); portInfo.portType = ((BigInteger)port.getValue()).intValue(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.2"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPIPAddress ipAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); portInfo.localIP = ipAddress.toString(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.3"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPInteger port = (SNMPInteger)variablePair.getSNMPObjectAt(1); portInfo.localPort = ((BigInteger)port.getValue()).intValue(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.4"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPIPAddress ipAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); portInfo.remoteIP = ipAddress.toString(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.5"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPInteger port = (SNMPInteger)variablePair.getSNMPObjectAt(1); portInfo.remotePort = ((BigInteger)port.getValue()).intValue(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.6"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPIPAddress ipAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); portInfo.gatewayIP = ipAddress.toString(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.7"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPInteger port = (SNMPInteger)variablePair.getSNMPObjectAt(1); portInfo.gatewayPort = ((BigInteger)port.getValue()).intValue(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } // skip 8, 9, 10 oidBase = "1.3.6.1.4.1.731.100.3.1.1.8"; while(oid.startsWith(oidBase)) { i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.9"; while(oid.startsWith(oidBase)) { i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.10"; while(oid.startsWith(oidBase)) { i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } oidBase = "1.3.6.1.4.1.731.100.3.1.1.11"; while(oid.startsWith(oidBase)) { // get index String tableIndex = oid.substring(oidBase.length() + 1); // modify PortInfo in hashtable PortInfo portInfo = (PortInfo)this.get(tableIndex); SNMPInteger lifetime = (SNMPInteger)variablePair.getSNMPObjectAt(1); portInfo.lifetime = ((BigInteger)lifetime.getValue()).intValue(); i++; if (i >= varBindList.size()) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); oid = snmpOID.toString(); } } } public void setMACAddresses(ArpInfoTreeMap arpInfoTreeMap) { // for each entry in the portInfoMap, find its corresponding MAC address in the arpInfoMap Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { PortInfo portInfo = (PortInfo)iterator.next(); String ipAddress = portInfo.localIP; // find ArpInfo object corresponding to IP address ArpInfo arpInfo = (ArpInfo)arpInfoTreeMap.get(ipAddress); if (arpInfo != null) { portInfo.localMAC = arpInfo.macAddress; } } } public String toString() { String returnValue = new String(); Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { PortInfo portInfo = (PortInfo)iterator.next(); returnValue += portInfo.toString() + "\n"; } return returnValue; } }