hostmon-2.1/0000755000175000017500000000000007744620601012407 5ustar julienjulienhostmon-2.1/AboutDialog.java0000664000175000017500000001200607743637750015461 0ustar julienjulien/* * Wireless Host Monitor * * 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.*; public class AboutDialog extends JDialog implements ActionListener, Runnable { private JLabel aboutLabel1 = new JLabel(" "); private JLabel aboutLabel2 = new JLabel(" "); private JLabel aboutLabel3 = new JLabel(" "); private JLabel aboutLabel4 = new JLabel(" "); private String aboutString1 = "Wireless Host Monitoring Utility"; private String aboutString2 = "Version 2.1"; private String aboutString3 = "J. Sevy"; private String aboutString4 = "October 2003"; private JButton okButton; Thread displayThread; public AboutDialog(JFrame parent) { super(parent, "About...", true /*modal*/); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); Font titleFont = new Font("SansSerif",Font.BOLD + Font.ITALIC, 12); Font labelFont = new Font("SansSerif",Font.PLAIN, 10); aboutLabel1.setText(aboutString1); aboutLabel2.setText(aboutString2); aboutLabel3.setText(aboutString3); aboutLabel4.setText(aboutString4); aboutLabel1.setFont(titleFont); aboutLabel2.setFont(labelFont); aboutLabel3.setFont(labelFont); aboutLabel4.setFont(labelFont); 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; JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(aboutLabel1, c); aboutPanel.add(aboutLabel1); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(aboutLabel2, c); aboutPanel.add(aboutLabel2); c.gridx = 1; c.gridy = 3; theLayout.setConstraints(aboutLabel3, c); aboutPanel.add(aboutLabel3); c.gridx = 1; c.gridy = 4; theLayout.setConstraints(aboutLabel4, c); aboutPanel.add(aboutLabel4); okButton = new JButton("OK"); okButton.setActionCommand("ok"); okButton.addActionListener(this); this.getRootPane().setDefaultButton(okButton); this.getContentPane().setLayout(theLayout); c.insets = new Insets(8,8,8,8); 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, 180); } 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 { Color textColor = new Color(255, 0, 255); aboutLabel1.setForeground(textColor); /* aboutLabel1.setSize(0, 30); for (int i = 0; i < this.getWidth() - 20; i++) { aboutLabel1.setSize(i, 30); Thread.currentThread().sleep(6); } */ // change color of other strings... int numSteps = 255; for (int i = 0; i < numSteps; i++) { textColor = new Color(255, 255-i, i); aboutLabel2.setForeground(textColor); aboutLabel3.setForeground(textColor); aboutLabel4.setForeground(textColor); Thread.currentThread().sleep(20); } } catch(Exception e) { // don't bother informing of exception; just exit... //System.out.println(e); } // later! } }hostmon-2.1/HostInfo.java0000664000175000017500000000201307734712710015003 0ustar julienjulien/* * Wireless Host Monitor * * 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.*; public class HostInfo { public MacAddress macAddress; public int timeAssociated; public String name; public String ipAddress; public boolean known; }hostmon-2.1/HostMonitor.java0000644000175000017500000007542707743637713015571 0ustar julienjulien/* * Wireless Host Monitor * * 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 HostMonitor extends JFrame implements ActionListener, Runnable { JButton newPreferencesButton, discoverDevicesButton, knownHostsButton; JTextField airportInternalIPField; JTextField airportExternalIPField, airportNameField, airportLocationField; JPanel hostPanel; MenuBar theMenubar; Menu fileMenu; MenuItem quitItem, aboutItem, savePreferencesItem; JTextArea messagesArea; JTextAreaWriter messagesAreaWriter; HostInfoTable hostInfoTable; Thread inspectionThread; Preferences2 preferences; boolean preferencesSaved = true; String preferencesFilename = "HostMonitor.ini"; TreeMap knownHostTreeMap; boolean knownHostsSaved = true; String knownHostFilename = "KnownHosts.ini"; SNMPv1CommunicationInterface communicationInterface; private Vector changeListeners; HostInfoTreeMap currentInfo; HostInfoRetriever currentRetriever; // WindowCloseAdapter to catch window close-box closings private class WindowCloseAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { checkSettings(); System.exit(0); } } public HostMonitor() { // read any settings that have previously been saved readPreferences(preferencesFilename); readKnownHostInfo(knownHostFilename); changeListeners = new Vector(); currentInfo = new HostInfoTreeMap(); // 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(); this.show(); // put up dialog to solicit new settings; this also sets up stuff as indicated if (getPreferences() == false) { messagesArea.setText("Problem with supplied information; set options again"); } } public void addChangeListener(HostInfoChangeListener changeListener) { if (!changeListeners.contains(changeListener)) changeListeners.add(changeListener); } public void removeChangeListener(HostInfoChangeListener changeListener) { if (changeListeners.contains(changeListener)) changeListeners.remove(changeListener); } public void removeAllChangeListeners() { changeListeners.removeAllElements(); } 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("Host Monitor"); 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 settings"); 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(12); airportInternalIPField.setText("10.0.1.1"); airportInternalIPField.setEditable(false); airportInternalIPField.setMinimumSize(airportInternalIPField.getPreferredSize()); JLabel airportExternalIPLabel = new JLabel("Base station WAN address:"); airportExternalIPField = new JTextField(12); airportExternalIPField.setEditable(false); airportExternalIPField.setMinimumSize(airportExternalIPField.getPreferredSize()); JLabel airportNameLabel = new JLabel("Base station name:"); airportNameField = new JTextField(20); airportNameField.setEditable(false); airportNameField.setMinimumSize(airportNameField.getPreferredSize()); JLabel airportLocationLabel = new JLabel("Base station location:"); airportLocationField = new JTextField(20); airportLocationField.setEditable(false); airportLocationField.setMinimumSize(airportLocationField.getPreferredSize()); newPreferencesButton = new JButton("Change settings"); newPreferencesButton.setActionCommand("new preferences"); newPreferencesButton.addActionListener(this); discoverDevicesButton = new JButton("Discover devices"); discoverDevicesButton.setActionCommand("discover devices"); discoverDevicesButton.addActionListener(this); knownHostsButton = new JButton("Edit known hosts"); knownHostsButton.setActionCommand("edit known hosts"); knownHostsButton.addActionListener(this); hostInfoTable = new HostInfoTable(currentInfo, this); hostInfoTable.setMinimumSize(hostInfoTable.getPreferredSize()); // 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.gridx = 1; c.gridy = 1; theLayout.setConstraints(newPreferencesButton, c); buttonPanel.add(newPreferencesButton); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(knownHostsButton, c); buttonPanel.add(knownHostsButton); // 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); messagesArea.setMinimumSize(messagesArea.getPreferredSize()); JScrollPane messagesScroll = new JScrollPane(messagesArea); messagesScroll.setMinimumSize(messagesScroll.getPreferredSize()); 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(hostInfoTable, c); this.getContentPane().add(hostInfoTable); 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 2.1 J. Sevy, October 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")) { checkSettings(); System.exit(0); } if (command.equals("about")) { AboutDialog aboutDialog = new AboutDialog(this); } if (command.equals("discover devices")) { AirportDiscoverer discoverer = new AirportDiscoverer(); } if (command.equals("edit known hosts")) { if ( (theEvent.getSource() instanceof JDataButton) && (((JDataButton)theEvent.getSource()).getData() instanceof MacAddress) ) { JDataButton button = (JDataButton)theEvent.getSource(); MacAddress macAddress = (MacAddress)button.getData(); // create new known host KnownHostInfo newKnownHostInfo = new KnownHostInfo("", macAddress); // bring up dialog with new known host added editKnownHostInfo(newKnownHostInfo); } else { editKnownHostInfo(); } } if (command.equals("new preferences")) { getPreferences(); } if (command.equals("save settings")) { saveSettings(); } } private void editKnownHostInfo(KnownHostInfo newKnownHostInfo) { KnownHostDialog knownHostDialog = new KnownHostDialog(this, knownHostTreeMap); knownHostDialog.addHost(newKnownHostInfo); // now setup and display dialog knownHostDialog.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 = knownHostDialog.getSize(); dim.height += 20; dim.width += 20; knownHostDialog.setSize(dim); knownHostDialog.show(); // on return, get known host info if (!knownHostDialog.isCanceled()) { knownHostTreeMap = knownHostDialog.getKnownHostTreeMap(); knownHostsSaved = false; // new known host info will be used when info next retrieved } } private void editKnownHostInfo() { KnownHostDialog knownHostDialog = new KnownHostDialog(this, knownHostTreeMap); knownHostDialog.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 = knownHostDialog.getSize(); dim.height += 20; dim.width += 20; knownHostDialog.setSize(dim); knownHostDialog.show(); // on return, get known host info if (!knownHostDialog.isCanceled()) { knownHostTreeMap = knownHostDialog.getKnownHostTreeMap(); knownHostsSaved = false; // new known host info will be used when info next retrieved } } private void getBaseStationInfo() throws 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); if (currentRetriever != null) { // get WAN IP address (corresponding to interface 3 on Snow and Graphite, 2 on Extreme) // need to retrieve table data with two separate gets, due to Snow AirPort retrieval bug int wanIndex = currentRetriever.getWANInterfaceIndex(); SNMPVarBindList ipAddressVarBindList = communicationInterface.retrieveMIBTable("1.3.6.1.2.1.4.20.1.1"); SNMPVarBindList interfaceIndexVarBindList = communicationInterface.retrieveMIBTable("1.3.6.1.2.1.4.20.1.2"); valueString = getInterfaceAddress(ipAddressVarBindList, interfaceIndexVarBindList, wanIndex); airportExternalIPField.setText(valueString); } } public String getInterfaceAddress(SNMPVarBindList ipAddressVarBindList, SNMPVarBindList interfaceIndexVarBindList, int interfaceIndex) { // make list of interface index / IP address pairs; // find entry corresponding to specified interface, and return its IP address int listSize = interfaceIndexVarBindList.size(); if (ipAddressVarBindList.size() < interfaceIndexVarBindList.size()) { listSize = ipAddressVarBindList.size(); } //System.out.println("ipAddressVarBindList: \n" + ipAddressVarBindList.toString()); //System.out.println("interfaceIndexVarBindList: \n" + interfaceIndexVarBindList.toString()); for (int i = 0; i < listSize; i++) { SNMPSequence variablePair = (SNMPSequence)ipAddressVarBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPIPAddress snmpIPAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); String ipAddress = snmpIPAddress.toString(); variablePair = (SNMPSequence)interfaceIndexVarBindList.getSNMPObjectAt(i); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPInteger snmpValue = (SNMPInteger)variablePair.getSNMPObjectAt(1); int retrievedInterfaceIndex = ((BigInteger)snmpValue.getValue()).intValue(); // see if have entry for desired interface index if (retrievedInterfaceIndex == interfaceIndex) { return ipAddress; } } // if get here, didn't find it... return ""; } public String oldGetInterfaceAddress(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 specified interface, 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(HostInfoTreeMap newInfo) { // update displayed info //messagesArea.append(newInfo.toString()); hostInfoTable.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(HostInfoTreeMap oldInfo, HostInfoTreeMap newInfo) { // just call the processPortInfoChange method of each listener for (int i = 0; i < changeListeners.size(); i++) { try { ((HostInfoChangeListener)changeListeners.elementAt(i)).processHostInfoChange(oldInfo, newInfo); } catch (HostInfoChangeException e) { messagesArea.append("Problem processing retrieved info: " + e.getMessage()); } } } public void run() { while(!Thread.currentThread().isInterrupted()) { try { // retrieve current info from base station HostInfoTreeMap newInfo; // get base station info (name, location, etc) getBaseStationInfo(); // if no retriever assigned, throw exception if (currentRetriever == null) throw new IOException("No access point type specified"); // get info on attached hosts, using current retriever newInfo = currentRetriever.getHostInfo(communicationInterface); // fill in host names newInfo.setHostNames(knownHostTreeMap); 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: " + e + "\n"); } catch (Exception e) { messagesArea.setText("Error retrieving information: " + e + "\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 checkSettings() { if (preferencesSaved == false) { // put up dialog to ask if settings should be saved if (JOptionPane.showConfirmDialog(this, "Save current base station settings?","Save settings?",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { savePreferences(preferencesFilename); } } if (knownHostsSaved == false) { // put up dialog to ask if settings should be saved if (JOptionPane.showConfirmDialog(this, "Save current known host information?","Save known hosts?",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { saveKnownHosts(knownHostFilename); } } } private void saveSettings() { savePreferences(preferencesFilename); saveKnownHosts(knownHostFilename); } private boolean getPreferences() { // get list of registered retrievers TreeMap retrievers = HostInfoRetriever.getRetrievers(); String[] retrieverNames = new String[retrievers.size()]; retrieverNames = (String[])retrievers.keySet().toArray(retrieverNames); PreferencesDialog theDialog = new PreferencesDialog(this, preferences, retrieverNames); if (!theDialog.isCancelled()) { // stop thread if needed if (inspectionThread.isAlive()) { inspectionThread.interrupt(); } // get preferences Preferences2 newPreferences = theDialog.getPreferences(); try { if (!newPreferences.equals(preferences)) preferencesSaved = false; // determine which retriever should be used currentRetriever = (HostInfoRetriever)retrievers.get(newPreferences.accessPointType); 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(s) this.removeAllChangeListeners(); // create and add new action object(s) if (newPreferences.logFlag == true) { // add logger HostInfoLogger logger = new HostInfoLogger(newPreferences.logFile, newPreferences.logMode); this.addChangeListener(logger); } if (newPreferences.beepNotifyFlag == true) { HostInfoBeepAlerter changeBeeper = new HostInfoBeepAlerter(newPreferences.notifyMode); changeListeners.add(changeBeeper); } if (newPreferences.emailNotifyFlag == true) { HostInfoChangeEmailer changeEmailer = new HostInfoChangeEmailer(newPreferences.emailAddress, newPreferences.emailSMTPHost, newPreferences.notifyMode, new JTextAreaWriter(messagesArea)); 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 void savePreferences(String fileName) { // save into file HostMonitor.ini ObjectOutputStream outStream; try { outStream = new ObjectOutputStream(new FileOutputStream(fileName)); outStream.writeObject(preferences); outStream.flush(); outStream.close(); preferencesSaved = true; } catch (Exception e) { // oh well... messagesArea.setText("Couldn't write base station settings: " + e.toString()); System.out.println("Couldn't write base station settings: " + e.toString()); preferencesSaved = false; } } private void saveKnownHosts(String fileName) { // save into file HostMonitor.ini ObjectOutputStream outStream; try { outStream = new ObjectOutputStream(new FileOutputStream(fileName)); outStream.writeObject(knownHostTreeMap); outStream.flush(); outStream.close(); knownHostsSaved = true; } catch (Exception e) { // oh well... messagesArea.setText("Couldn't write known host info: " + e.toString()); System.out.println("Couldn't write known host info: " + e.toString()); knownHostsSaved = false; } } private void readPreferences(String fileName) { // read from file fileName try { ObjectInputStream inStream = new ObjectInputStream(new FileInputStream(fileName)); Object preferencesObject = inStream.readObject(); if (preferencesObject instanceof Preferences2) { Preferences2 retrievedPreferences = (Preferences2)preferencesObject; preferences = new Preferences2((Preferences2)preferencesObject); preferencesSaved = true; } else if (preferencesObject instanceof Preferences) { preferences = new Preferences2((Preferences)preferencesObject); preferencesSaved = false; } else { throw new ClassCastException("Didn't recognize class of stored preferences"); } inStream.close(); } catch (Exception e) { // couldn't read; just return empty settings //messagesArea.setText("Couldn't read settings: " + e.toString()); //System.out.println("Couldn't read settings: " + e.toString()); preferences = new Preferences2(); preferencesSaved = false; } } private void readKnownHostInfo(String fileName) { // read from supplied file try { ObjectInputStream inStream = new ObjectInputStream(new FileInputStream(fileName)); knownHostTreeMap = (TreeMap)inStream.readObject(); inStream.close(); knownHostsSaved = true; } catch (Exception e) { // couldn't read; just return empty treemap //messagesArea.setText("Couldn't read known host info: " + e.toString()); System.out.println("Couldn't read known host info: " + e.toString()); knownHostTreeMap = new TreeMap(); knownHostsSaved = true; } } public static void main(String args[]) { try { HostMonitor theApp = new HostMonitor(); } catch (Exception e) {} } }hostmon-2.1/snmp/0000755000175000017500000000000007735202257013367 5ustar julienjulienhostmon-2.1/snmp/SNMPBERCodec.java0000644000175000017500000002137407725757454016322 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 SNMPBITSTRING: { return new SNMPBitString(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. Throws an SNMPBadValueException if there's * any problem with the extraction. */ public static SNMPTLV extractNextTLV(byte[] enc, int position) throws SNMPBadValueException { SNMPTLV nextTLV = new SNMPTLV(); int currentPos = position; try { // 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; } catch (Exception e) { // whatever the exception, throw an SNMPBadValueException throw new SNMPBadValueException("Problem while decoding BER"); } } /** * 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(); } }hostmon-2.1/snmp/SNMPBadValueException.java0000644000175000017500000000366707522113626020301 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); } }hostmon-2.1/snmp/SNMPCounter32.java0000644000175000017500000000750307522113662016514 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 "); } }hostmon-2.1/snmp/SNMPCounter64.java0000644000175000017500000000754207522113673016526 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 "); } }hostmon-2.1/snmp/SNMPGauge32.java0000644000175000017500000000741607522113710016122 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 "); } }hostmon-2.1/snmp/SNMPGetException.java0000644000175000017500000000461407732471644017340 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 SNMPRequestException { public SNMPGetException() { super("", 0, 0); } /** * Create exception with message string. */ public SNMPGetException(String s) { super(s, 0, 0); } /** * Create exception with errorIndex and errorStatus */ public SNMPGetException(int errorIndex, int errorStatus) { super(errorIndex, errorStatus); } /** * Create exception with errorIndex, errorStatus and message string */ public SNMPGetException(String message, int errorIndex, int errorStatus) { super(message, errorIndex, errorStatus); } }hostmon-2.1/snmp/SNMPIPAddress.java0000644000175000017500000001206207522113744016543 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 "); } } }hostmon-2.1/snmp/SNMPInteger.java0000644000175000017500000001145707522113734016330 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()); } }hostmon-2.1/snmp/SNMPMessage.java0000644000175000017500000001443007702143375016315 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; } /** * Utility method which returns the PDU contained in the SNMP message as an SNMPTrapPDU. The pdu is the * third component of the sequence, after the version and community name. */ 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; } /** * Utility method which returns the community name contained in the SNMP message. The community name is the * second component of the sequence, after the version. */ public String getCommunityName() throws SNMPBadValueException { Vector contents = (Vector)(this.getValue()); Object communityName = contents.elementAt(1); if (!(communityName instanceof SNMPOctetString)) { throw new SNMPBadValueException("Wrong SNMP type for community name in message: expected SNMPOctetString, have " + communityName.getClass().toString()); } return ((SNMPOctetString)communityName).toString(); } }hostmon-2.1/snmp/SNMPNSAPAddress.java0000644000175000017500000001170607522113762017000 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 "); } } }hostmon-2.1/snmp/SNMPNull.java0000644000175000017500000000475007522113772015645 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"); } }hostmon-2.1/snmp/SNMPObject.java0000644000175000017500000000450507522114006016126 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(); }hostmon-2.1/snmp/SNMPObjectIdentifier.java0000644000175000017500000002261407522114015020132 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; } }hostmon-2.1/snmp/SNMPOctetString.java0000644000175000017500000001235307625231416017176 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; } }hostmon-2.1/snmp/SNMPPDU.java0000644000175000017500000001434507715310222015355 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(); } /** * A utility method that returns the PDU type of this PDU. */ public byte getPDUType() { return tag; } }hostmon-2.1/snmp/SNMPSequence.java0000644000175000017500000001446007522114043016472 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; } }hostmon-2.1/snmp/SNMPSetException.java0000644000175000017500000000462207717465422017353 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 SNMPRequestException { /* public SNMPSetException() { super(); } */ /** * Create exception with message string. */ /* public SNMPSetException(String s) { super(s); } */ /** * Create exception with errorIndex and errorStatus */ public SNMPSetException(int errorIndex, int errorStatus) { super(errorIndex, errorStatus); } /** * Create exception with errorIndex, errorStatus and message string */ public SNMPSetException(String message, int errorIndex, int errorStatus) { super(message, errorIndex, errorStatus); } }hostmon-2.1/snmp/SNMPTLV.java0000644000175000017500000000330607522114073015367 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; }hostmon-2.1/snmp/SNMPTimeTicks.java0000644000175000017500000000377407522114062016625 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; } }hostmon-2.1/snmp/SNMPUInteger32.java0000644000175000017500000000740007522114124016605 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 "); } }hostmon-2.1/snmp/SNMPUnknownObject.java0000644000175000017500000000613607522114134017512 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); } }hostmon-2.1/snmp/SNMPVarBindList.java0000644000175000017500000000516507522114172017110 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; } }hostmon-2.1/snmp/SNMPVariablePair.java0000644000175000017500000000502407522114202017254 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); } }hostmon-2.1/snmp/SNMPv1CommunicationInterface.java0000644000175000017500000011521607735176151021636 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 private int receiveBufferSize = 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[receiveBufferSize], receiveBufferSize); 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), SNMPGetException thrown * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException * @throws SNMPGetException Thrown if supplied OID has value that can't be retrieved */ 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); while (true) // wait until receive reply for requestID & OID (or error) { DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); 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", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); 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 values corresponding to the object identifiers * given in the array 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), SNMPGetException thrown * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException * @throws SNMPGetException Thrown if one of supplied OIDs has value that can't be retrieved */ public SNMPVarBindList getMIBEntry(String[] itemID) throws IOException, SNMPBadValueException, SNMPGetException { // send GetRequest to specified host to retrieve values of specified object identifiers SNMPVarBindList retrievedVars = new SNMPVarBindList(); SNMPSequence varList = new SNMPSequence(); int errorStatus = 0; int errorIndex = 0; for (int i = 0; i < itemID.length; i++) { SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID[i]); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); 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); while (true) // wait until receive reply for requestID & OID (or error) { DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); 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) { // determine error index errorIndex = receivedPDU.getErrorIndex(); throw new SNMPGetException("OID " + itemID[errorIndex - 1] + " not available for retrieval", errorIndex, receivedPDU.getErrorStatus()); } // copy info from retrieved sequence to var bind list varList = receivedPDU.getVarBindList(); for (int i = 0; i < varList.size(); i++) { SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(i)); SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0)); SNMPObject newValue = newPair.getSNMPObjectAt(1); if (newObjectIdentifier.toString().equals(itemID[i])) { retrievedVars.addSNMPObject(newPair); } else { // wrong OID; throw GetException throw new SNMPGetException("OID " + itemID[i] + " expected at index " + i + ", OID " + newObjectIdentifier + " received", i+1, SNMPRequestException.FAILED); } } 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 * @throws SNMPGetException Thrown if one the OID following the supplied OID has value that can't be retrieved */ 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); while (true) // wait until receive reply for requestID & OID (or error) { DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); 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", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); 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; } /** * Retrieve the MIB variable value corresponding to the object identifiers following those * given in the itemID array (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), SNMPGetException thrown * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException * @throws SNMPGetException Thrown if OID following one of supplied OIDs has value that can't be retrieved */ public SNMPVarBindList getNextMIBEntry(String[] itemID) throws IOException, SNMPBadValueException, SNMPGetException { // send GetRequest to specified host to retrieve values of specified object identifiers SNMPVarBindList retrievedVars = new SNMPVarBindList(); SNMPSequence varList = new SNMPSequence(); int errorStatus = 0; int errorIndex = 0; for (int i = 0; i < itemID.length; i++) { SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID[i]); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); 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); while (true) // wait until receive reply for requestID & OID (or error) { DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); 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) { // determine error index errorIndex = receivedPDU.getErrorIndex(); throw new SNMPGetException("OID following " + itemID[errorIndex - 1] + " not available for retrieval", errorIndex, receivedPDU.getErrorStatus()); } // copy info from retrieved sequence to var bind list varList = receivedPDU.getVarBindList(); for (int i = 0; i < varList.size(); i++) { SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(i)); 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); while (true) // wait until receive reply for correct OID (or error) { DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); 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.", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); case 2: throw new SNMPSetException("OID " + itemID + " not available for setting.", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); case 3: throw new SNMPSetException("Bad value supplied for OID " + itemID + ".", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); case 4: throw new SNMPSetException("OID " + itemID + " read-only.", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); default: throw new SNMPSetException("Error setting OID " + itemID + ".", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); } } 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; } /** * Set the MIB variable values of the supplied object identifiers given in the * itemID array (in dotted-integer notation). Return SNMPVarBindList 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 { // check that OID and value arrays have same size if (itemID.length != newValue.length) { throw new SNMPSetException("OID and value arrays must have same size", 0, SNMPRequestException.FAILED); } // send SetRequest to specified host to set values of specified object identifiers SNMPVarBindList retrievedVars = new SNMPVarBindList(); SNMPSequence varList = new SNMPSequence(); int errorStatus = 0; int errorIndex = 0; for (int i = 0; i < itemID.length; i++) { SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID[i]); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, newValue[i]); 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); while (true) // wait until receive reply for correct OID (or error) { DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize); 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) { errorIndex = receivedPDU.getErrorIndex(); switch (receivedPDU.getErrorStatus()) { case 1: throw new SNMPSetException("Value supplied for OID " + itemID[errorIndex - 1] + " too big.", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); case 2: throw new SNMPSetException("OID " + itemID[errorIndex - 1] + " not available for setting.", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); case 3: throw new SNMPSetException("Bad value supplied for OID " + itemID[errorIndex - 1] + ".", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); case 4: throw new SNMPSetException("OID " + itemID[errorIndex - 1] + " read-only.", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); default: throw new SNMPSetException("Error setting OID " + itemID[errorIndex - 1] + ".", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus()); } } // copy info from retrieved sequence to var bind list varList = receivedPDU.getVarBindList(); for (int i = 0; i < varList.size(); i++) { SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(i)); SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0)); //SNMPObject receivedValue = newPair.getSNMPObjectAt(1); if (newObjectIdentifier.toString().equals(itemID[i])) { retrievedVars.addSNMPObject(newPair); } else { // wrong OID; throw GetException throw new SNMPSetException("OID " + itemID[i] + " expected at index " + i + ", OID " + newObjectIdentifier + " received", i+1, SNMPRequestException.FAILED); } } 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[receiveBufferSize], receiveBufferSize); 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; } /** * Retrieve all MIB variable values whose OIDs start with the supplied baseIDs. The normal way for * this to be used is for the base OID array to consist of the base OIDs of the columns of a table. * This method will then retrieve all of the entries of the table corresponding to these columns, one * row at a time (i.e., the entries for each row will be retrieved in a single SNMP request). This * will retrieve the table data as an SNMPVarBindList object consisting of sequence of SNMPVariablePairs, * with the entries for each row grouped together. This may provide a more convenient arrangement of * the table data than the simpler retrieveMIBTable method taking a single OID as argument; in addition, * it's more efficient, requiring one SNMP request per row rather than one request per entry. * Uses SNMPGetNextRequests to retrieve variable values for each row in sequence. * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException * @throws SNMPGetException Thrown if incomplete row retrieved */ 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; SNMPObjectIdentifier[] requestedObjectIdentifier = new SNMPObjectIdentifier[baseID.length]; for (int i = 0; i < baseID.length; i++) { requestedObjectIdentifier[i] = new SNMPObjectIdentifier(baseID[i]); } retrievalLoop: while (errorStatus == 0) { SNMPSequence varList = new SNMPSequence(); for (int i = 0; i < requestedObjectIdentifier.length; i++) { SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier[i], new SNMPInteger(0)); 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[receiveBufferSize], receiveBufferSize); dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); /* System.out.println("Received bytes:"); for (int i = 0; i < 128; ++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 for error index 1, just break - assume there are no additional OIDs // to retrieve. If index is other than 1, throw exception if (receivedPDU.getErrorStatus() != 0) { int retrievedErrorIndex = receivedPDU.getErrorIndex(); if (retrievedErrorIndex == 1) { break retrievalLoop; } else { throw new SNMPGetException("OID following " + requestedObjectIdentifier[retrievedErrorIndex - 1] + " not available for retrieval", retrievedErrorIndex, receivedPDU.getErrorStatus()); } } // copy info from retrieved sequence to var bind list varList = receivedPDU.getVarBindList(); // make sure got the right number of vars in reply; if not, throw GetException if(varList.size() != requestedObjectIdentifier.length) { throw new SNMPGetException("Incomplete row of table received", 0, SNMPRequestException.FAILED); } // copy the retrieved variable pairs into retrievedVars for (int i = 0; i < varList.size(); i++) { SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(i)); 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[i])) { if (i == 0) { // it's the first element of the row; just break break retrievalLoop; } else { // it's a subsequent row element; throw exception throw new SNMPGetException("Incomplete row of table received", i+1, SNMPRequestException.FAILED); } } retrievedVars.addSNMPObject(newPair); // set requested identifiers array to current identifiers to do get-next for next row requestedObjectIdentifier[i] = newObjectIdentifier; } requestID++; } } return retrievedVars; } /** * Set the size of the buffer used to receive response packets. RFC 1157 stipulates that an SNMP * implementation must be able to receive packets of at least 484 bytes, so if you try to set the * size to a value less than this, the receive buffer size will be set to 484 bytes. In addition, * the maximum size of a UDP packet payload is 65535 bytes, so setting the buffer to a larger size * will just waste memory. The default value is 512 bytes. The value may need to be increased if * get-requests are issued for multiple OIDs. */ public void setReceiveBufferSize(int receiveBufferSize) { if (receiveBufferSize >= 484) { this.receiveBufferSize = receiveBufferSize; } else { this.receiveBufferSize = 484; } } /** * Returns the current size of the buffer used to receive response packets. */ public int getReceiveBufferSize() { return this.receiveBufferSize; } }hostmon-2.1/snmp/package.html0000644000175000017500000000362407503646713015657 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. hostmon-2.1/snmp/SNMPTrapPDU.java0000644000175000017500000002152107522114114016174 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(); } }hostmon-2.1/snmp/SNMPBitString.java0000644000175000017500000000446407625233047016644 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; /** * Class representing a general string of bits. */ public class SNMPBitString extends SNMPOctetString { protected byte tag = SNMPBERCodec.SNMPBITSTRING; /** * Create a zero-length bit string. */ public SNMPBitString() { this.data = new byte[0]; } /** * Create a bit string from the bytes of the supplied String. */ public SNMPBitString(String stringData) { this.data = stringData.getBytes(); } /** * Create a bit 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 a bit string is just the raw bytes. */ public SNMPBitString(byte[] enc) { extractFromBEREncoding(enc); } }hostmon-2.1/snmp/SNMPRequestException.java0000644000175000017500000000545307717465451020255 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 request to get or 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. errorStatus parameter allows the reason for the failure to be specified, and errorIndex * allows the index of the failed OID to be specified. */ public class SNMPRequestException extends SNMPException { public static final int NO_ERROR = 0; public static final int VALUE_TOO_BIG = 1; public static final int VALUE_NOT_AVAILABLE = 2; public static final int BAD_VALUE = 3; public static final int VALUE_READ_ONLY = 4; public static final int FAILED = 5; public int errorIndex = 0; public int errorStatus = 0; /** * Create exception with errorIndex, errorStatus */ public SNMPRequestException(int errorIndex, int errorStatus) { super(); this.errorIndex = errorIndex; this.errorStatus = errorStatus; } /** * Create exception with errorIndex, errorStatus, and message string */ public SNMPRequestException(String message, int errorIndex, int errorStatus) { super(message); this.errorIndex = errorIndex; this.errorStatus = errorStatus; } }hostmon-2.1/snmp/SNMPException.java0000644000175000017500000000373707717464206016704 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 or get value of SNMP OID fails. Reason could be that * specified variable not supported by device, or that supplied community name has insufficient * privileges. */ public class SNMPException extends Exception { public SNMPException() { super(); } /** * Create exception with message string. */ public SNMPException(String s) { super(s); } }hostmon-2.1/PreferencesDialog.java0000644000175000017500000003557307743373302016652 0ustar julienjulien/* * Wireless Host Monitor * * 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.*; import java.util.*; public class PreferencesDialog extends JDialog implements ActionListener { JTextField ipAddressField; JPasswordField passwordField; JTextField intervalField; JLabel ipAddressLabel; JLabel passwordLabel; JLabel intervalLabel; JLabel accessPointTypeLabel; JComboBox accessPointTypeComboBox; JCheckBox logCheckBox; JLabel logFileLabel; JTextField logFileField; JButton chooseLogFileButton; JRadioButton logAllButton, logUnknownButton; JCheckBox notifyCheckBox; JRadioButton notifyAllButton, notifyUnknownButton; JCheckBox notifyBeepCheckBox; JCheckBox notifyEmailCheckBox; JLabel notifyEmailLabel; JTextField notifyEmailField; JLabel notifySMTPServerLabel; JTextField notifySMTPServerField; JButton okButton, cancelButton; boolean cancelled = false; Preferences2 newPrefs; public PreferencesDialog(Frame owner, Preferences2 currentPreferences, String[] accessPointTypes) { // create as modal dialog super(owner, "Preferences", true); // set new prefs to current newPrefs = currentPreferences; ipAddressField = new JTextField(12); ipAddressLabel = new JLabel("Base station IP address:"); ipAddressField.setText(currentPreferences.ipAddress); ipAddressField.setMinimumSize(ipAddressField.getPreferredSize()); passwordField = new JPasswordField(12); passwordLabel = new JLabel("Base station password:"); passwordField.setText(""); passwordField.setMinimumSize(passwordField.getPreferredSize()); intervalField = new JTextField(12); intervalLabel = new JLabel("Base station query interval (seconds):"); intervalField.setText("" + currentPreferences.queryInterval); intervalField.setMinimumSize(intervalField.getPreferredSize()); logCheckBox = new JCheckBox("Log associated host information"); logCheckBox.setSelected(currentPreferences.logFlag); logAllButton = new JRadioButton("Log all associated hosts"); logUnknownButton = new JRadioButton("Log only unknown associated hosts"); ButtonGroup logButtonGroup = new ButtonGroup(); logButtonGroup.add(logAllButton); logButtonGroup.add(logUnknownButton); if (currentPreferences.logMode == Preferences2.LOG_ALL) { logAllButton.setSelected(true); } else { logUnknownButton.setSelected(true); } logFileField = new JTextField(12); logFileLabel = new JLabel("Log file:"); logFileField.setText(currentPreferences.logFile); logFileField.setMinimumSize(logFileField.getPreferredSize()); chooseLogFileButton = new JButton("Choose file..."); chooseLogFileButton.setActionCommand("choose log file"); chooseLogFileButton.addActionListener(this); notifyCheckBox = new JCheckBox("Notify when new hosts appear"); notifyCheckBox.setSelected(currentPreferences.notifyFlag); notifyAllButton = new JRadioButton("Notify for all associated hosts"); notifyUnknownButton = new JRadioButton("Notify only for unknown associated hosts"); ButtonGroup notifyButtonGroup = new ButtonGroup(); notifyButtonGroup.add(notifyAllButton); notifyButtonGroup.add(notifyUnknownButton); if (currentPreferences.notifyMode == Preferences2.NOTIFY_ALL) { notifyAllButton.setSelected(true); } else { notifyUnknownButton.setSelected(true); } notifyBeepCheckBox = new JCheckBox("Beep when new hosts appear"); notifyBeepCheckBox.setSelected(currentPreferences.beepNotifyFlag); notifyEmailCheckBox = new JCheckBox("Send email when new hosts appear"); notifyEmailCheckBox.setSelected(currentPreferences.emailNotifyFlag); notifyEmailField = new JTextField(12); notifyEmailLabel = new JLabel("Email address:"); notifyEmailField.setText(currentPreferences.emailAddress); notifyEmailField.setMinimumSize(notifyEmailField.getPreferredSize()); notifySMTPServerField = new JTextField(12); notifySMTPServerLabel = new JLabel("Email server (SMTP):"); notifySMTPServerField.setText(currentPreferences.emailSMTPHost); notifySMTPServerField.setMinimumSize(notifySMTPServerField.getPreferredSize()); okButton = new JButton("OK"); okButton.setActionCommand("ok"); okButton.addActionListener(this); this.getRootPane().setDefaultButton(okButton); cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(this); // populate combo box with access point types; set selected index to accessPointTypeComboBox = new JComboBox(accessPointTypes); accessPointTypeComboBox.setSelectedItem(currentPreferences.accessPointType); accessPointTypeLabel = new JLabel("Base station type:"); // 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; // set up panel for logging info InfoPanel logPanel = new InfoPanel(); // put stuff in panel logPanel.setLayout(theLayout); c.gridwidth = 3; c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(logUnknownButton, c); logPanel.add(logUnknownButton); c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(logAllButton, c); logPanel.add(logAllButton); c.gridwidth = 1; c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.EAST; theLayout.setConstraints(logFileLabel, c); logPanel.add(logFileLabel); c.gridx = 2; c.gridy = 3; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(logFileField, c); logPanel.add(logFileField); c.gridx = 3; c.gridy = 3; c.anchor = GridBagConstraints.CENTER; theLayout.setConstraints(chooseLogFileButton, c); logPanel.add(chooseLogFileButton); // make highlighting of panel dependent on logCheckBox logCheckBox.addItemListener(logPanel); logPanel.setEnabled(logCheckBox.isSelected()); // set up panel for email notifying when new host appears InfoPanel emailNotifyPanel = new InfoPanel(); emailNotifyPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.EAST; theLayout.setConstraints(notifyEmailLabel, c); emailNotifyPanel.add(notifyEmailLabel); c.gridx = 2; c.gridy = 1; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyEmailField, c); emailNotifyPanel.add(notifyEmailField); c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.EAST; theLayout.setConstraints(notifySMTPServerLabel, c); emailNotifyPanel.add(notifySMTPServerLabel); c.gridx = 2; c.gridy = 2; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifySMTPServerField, c); emailNotifyPanel.add(notifySMTPServerField); // make highlighting of panel dependent on logCheckBox logCheckBox.addItemListener(emailNotifyPanel); emailNotifyPanel.setEnabled(logCheckBox.isSelected()); // make highlighting of panel dependent on notifyCheckBox notifyEmailCheckBox.addItemListener(emailNotifyPanel); emailNotifyPanel.setEnabled(notifyEmailCheckBox.isSelected()); // set up panel for notifying when new host appears InfoPanel notifyPanel = new InfoPanel(); notifyPanel.setLayout(theLayout); c.gridwidth = 1; c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyUnknownButton, c); notifyPanel.add(notifyUnknownButton); c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyAllButton, c); notifyPanel.add(notifyAllButton); c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyBeepCheckBox, c); notifyPanel.add(notifyBeepCheckBox); c.gridx = 1; c.gridy = 4; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyEmailCheckBox, c); notifyPanel.add(notifyEmailCheckBox); c.gridx = 1; c.gridy = 5; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(emailNotifyPanel, c); notifyPanel.add(emailNotifyPanel); // make highlighting of panel dependent on notifyCheckBox notifyCheckBox.addItemListener(notifyPanel); notifyPanel.setEnabled(notifyCheckBox.isSelected()); this.getContentPane().setLayout(theLayout); c.anchor = GridBagConstraints.CENTER; c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.EAST; theLayout.setConstraints(ipAddressLabel, c); this.getContentPane().add(ipAddressLabel); c.gridx = 2; c.gridy = 1; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(ipAddressField, c); this.getContentPane().add(ipAddressField); c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.EAST; theLayout.setConstraints(passwordLabel, c); this.getContentPane().add(passwordLabel); c.gridx = 2; c.gridy = 2; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(passwordField, c); this.getContentPane().add(passwordField); c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.EAST; theLayout.setConstraints(accessPointTypeLabel, c); this.getContentPane().add(accessPointTypeLabel); c.gridx = 2; c.gridy = 3; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(accessPointTypeComboBox, c); this.getContentPane().add(accessPointTypeComboBox); c.gridwidth = 2; c.gridx = 1; c.gridy = 4; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(logCheckBox, c); this.getContentPane().add(logCheckBox); c.gridx = 1; c.gridy = 5; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(logPanel, c); this.getContentPane().add(logPanel); c.gridx = 1; c.gridy = 6; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyCheckBox, c); this.getContentPane().add(notifyCheckBox); c.gridx = 1; c.gridy = 7; c.anchor = GridBagConstraints.WEST; theLayout.setConstraints(notifyPanel, c); this.getContentPane().add(notifyPanel); c.gridwidth = 1; c.gridx = 1; c.gridy = 8; c.anchor = GridBagConstraints.CENTER; theLayout.setConstraints(okButton, c); this.getContentPane().add(okButton); c.gridx = 2; c.gridy = 8; c.anchor = GridBagConstraints.CENTER; 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(); } if (command == "choose log file") { FileDialog fd = new FileDialog((Frame)this.getOwner(), "Select log file...", FileDialog.LOAD); fd.setFile(logFileField.getText()); fd.show(); if (fd.getFile() != null) { logFileField.setText(fd.getFile()); } } } private boolean validateNewPreferences() { int interval; // check the interval parameter try { interval = Integer.parseInt(intervalField.getText()); if (interval <= 0) throw new NumberFormatException(); newPrefs = new Preferences2(); newPrefs.ipAddress = ipAddressField.getText(); newPrefs.password = passwordField.getText(); newPrefs.queryInterval = interval; newPrefs.accessPointType = (String)accessPointTypeComboBox.getSelectedItem(); if (logCheckBox.isSelected()) newPrefs.logFlag = true; else newPrefs.logFlag = false; if (logAllButton.isSelected()) newPrefs.logMode = Preferences2.LOG_ALL; else if (logUnknownButton.isSelected()) newPrefs.logMode = Preferences2.LOG_UNKNOWN; else newPrefs.logMode = Preferences2.LOG_NONE; newPrefs.logFile = logFileField.getText(); if (notifyCheckBox.isSelected()) newPrefs.notifyFlag = true; else newPrefs.notifyFlag = false; if (notifyAllButton.isSelected()) newPrefs.notifyMode = Preferences2.NOTIFY_ALL; else if (notifyUnknownButton.isSelected()) newPrefs.notifyMode = Preferences2.NOTIFY_UNKNOWN; else newPrefs.notifyMode = Preferences2.NOTIFY_NONE; if (notifyBeepCheckBox.isSelected()) newPrefs.beepNotifyFlag = true; else newPrefs.beepNotifyFlag = false; if (notifyEmailCheckBox.isSelected()) newPrefs.emailNotifyFlag = true; else newPrefs.emailNotifyFlag = false; newPrefs.emailAddress = notifyEmailField.getText(); newPrefs.emailSMTPHost = notifySMTPServerField.getText(); return true; } catch(NumberFormatException e) { JOptionPane.showMessageDialog(this, "Value supplied must be a positive integer."); return false; } } public Preferences2 getPreferences() { return newPrefs; } public boolean isCancelled() { return cancelled; } }hostmon-2.1/Preferences.java0000644000175000017500000000344607742115735015527 0ustar julienjulien/* * Wireless Host Monitor * * 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 String accessPointType; public Preferences() { ipAddress = ""; password = ""; queryInterval = 5; accessPointType = ""; } public boolean equals(Object otherPrefsObject) { if (!(otherPrefsObject instanceof Preferences)) { return false; } Preferences otherPrefs = (Preferences)otherPrefsObject; // compare all fields but passwords if ( (this.ipAddress.equals(otherPrefs.ipAddress)) && (this.queryInterval == otherPrefs.queryInterval) && (this.accessPointType.equals(otherPrefs.accessPointType)) ) { return true; } else { return false; } } }hostmon-2.1/AirportDiscoverer.java0000644000175000017500000001725107734712765016742 0ustar julienjulien/* * Wireless Host Monitor * * 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; } }hostmon-2.1/AirportDiscoveryInfo.java0000644000175000017500000000726407734713020017404 0ustar julienjulien/* * Wireless Host Monitor * * 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); } }hostmon-2.1/HostInfoTreeMap.java0000644000175000017500000001306107744571261016271 0ustar julienjulien/* * Wireless Host Monitor * * 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 HostInfoTreeMap extends TreeMap { public static final String UNKNOWN_HOST_NAME = "*****Unknown host*****"; public HostInfoTreeMap() { // create empty Hashtable super(); } public HostInfoTreeMap(SNMPVarBindList varBindList) { // create and populate Hashtable of HostInfo objects super(); for (int i = 0; i < varBindList.size(); i += 2) { SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPOctetString snmpMacAddress = (SNMPOctetString)variablePair.getSNMPObjectAt(1); MacAddress macAddress = new MacAddress((byte[])snmpMacAddress.getValue()); if ( (i+1) >= varBindList.size() ) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i+1); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPInteger snmpValue = (SNMPInteger)variablePair.getSNMPObjectAt(1); BigInteger timeAssociatedObject = (BigInteger)snmpValue.getValue(); int timeAssociated = timeAssociatedObject.intValue(); HostInfo hostInfo = new HostInfo(); hostInfo.macAddress = macAddress; hostInfo.timeAssociated = timeAssociated; // add new HostInfo object to hashtable this.put(macAddress, hostInfo); } } public HostInfoTreeMap(TreeMap hostInfoTreeMap) { // create and populate Hashtable of HostInfo objects, using supplied tree map super(hostInfoTreeMap); } public void setMACAddresses(ArpInfoTreeMap arpInfoTreeMap) { // for each entry in the hostInfoMap, find its corresponding MAC address in the arpInfoMap Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { HostInfo hostInfo = (HostInfo)iterator.next(); // find ArpInfo object corresponding to IP address ArpInfo arpInfo = (ArpInfo)arpInfoTreeMap.get(hostInfo.ipAddress); if (arpInfo != null) { hostInfo.macAddress = arpInfo.macAddress; } else { // no ARP entry; assume this is a spurious port map, and drop it iterator.remove(); //byte[] nullAddress = {0,0,0,0,0,0}; //hostInfo.macAddress = new MacAddress(nullAddress); } } } public void setIPAddresses(RarpInfoTreeMap rarpInfoTreeMap) { // for each entry in the hostInfoMap, find its corresponding MAC address in the arpInfoMap Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { HostInfo hostInfo = (HostInfo)iterator.next(); // find ArpInfo object corresponding to MAC address ArpInfo arpInfo = (ArpInfo)rarpInfoTreeMap.get(hostInfo.macAddress); if (arpInfo != null) { hostInfo.ipAddress = arpInfo.ipAddress; } else { // no IP address known; call it unknown hostInfo.ipAddress = "unknown"; } } } public void setHostNames(TreeMap knownHostTreeMap) { // for each entry in the hostInfoMap, find its corresponding name in the knownHostTreeMap Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { HostInfo hostInfo = (HostInfo)iterator.next(); // find ArpInfo object corresponding to MAC address KnownHostInfo knownHostInfo = (KnownHostInfo)knownHostTreeMap.get(hostInfo.macAddress); if (knownHostInfo != null) { hostInfo.name = knownHostInfo.name; hostInfo.known = true; } else { hostInfo.name = UNKNOWN_HOST_NAME; hostInfo.known = false; } } } public String toString() { String returnValue = new String(); Iterator iterator = this.values().iterator(); while (iterator.hasNext()) { HostInfo hostInfo = (HostInfo)iterator.next(); returnValue += hostInfo.toString() + "\n"; } return returnValue; } }hostmon-2.1/HostInfoTable.java0000644000175000017500000002357707744602317015775 0ustar julienjulien/* * Wireless Host Monitor * * 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 HostInfoTable extends JPanel { private Vector hostInfoVector; private JTable table; private AbstractTableModel tableModel; private JScrollPane scrollPane; private JDataButton addButton; /** * Table model which maintains simplified list of port mappings. */ private class HostTableModel extends AbstractTableModel { public int getColumnCount() { return 5; } public int getRowCount() { return hostInfoVector.size(); } public boolean isCellEditable(int row, int col) { if (col == 4) return true; else return false; } public String getColumnName(int col) { switch (col) { case 0: return "Host name"; case 1: return "MAC address"; case 2: return "IP address"; case 3: return "Time associated"; case 4: return "Add"; default: return ""; } } public Object getValueAt(int row, int col) { if (row < hostInfoVector.size()) { HostInfo hostInfo = (HostInfo)hostInfoVector.elementAt(row); switch (col) { case 0: return hostInfo.name; case 1: return hostInfo.macAddress.toString(); case 2: return hostInfo.ipAddress; case 3: return timeString(hostInfo.timeAssociated); case 4: { //return addButton; return ""; } default: return ""; } } else return ""; } public void setValueAt(Object newValue, int row, int col) { //System.out.println("setValueAt row = " + row + ", col = " + col); } } /** * Create new table based on data in hostInfoTreeMap. */ public HostInfoTable(HostInfoTreeMap hostInfoTreeMap, ActionListener hostEditorListener) { addButton = new JDataButton("Add"); addButton.setActionCommand("edit known hosts"); addButton.addActionListener(hostEditorListener); this.hostInfoVector = new Vector(hostInfoTreeMap.values()); table = new JTable(); tableModel = new HostTableModel(); table.setModel(tableModel); setColumnPreferredWidths(table); setAddHostRendererAndEditor(table); table.setPreferredScrollableViewportSize(new Dimension(600,300)); 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(HostInfoTreeMap hostInfoTreeMap) { this.hostInfoVector = new Vector(hostInfoTreeMap.values()); tableModel.fireTableDataChanged(); } private void setColumnPreferredWidths(JTable table) { TableModel tableModel = table.getModel(); TableColumnModel tableColumnModel = table.getColumnModel(); tableColumnModel.getColumn(0).setPreferredWidth(150); tableColumnModel.getColumn(1).setPreferredWidth(120); tableColumnModel.getColumn(2).setPreferredWidth(120); tableColumnModel.getColumn(3).setPreferredWidth(150); tableColumnModel.getColumn(4).setPreferredWidth(60); } private void oldSetColumnPreferredWidths(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); } } private void setAddHostRendererAndEditor(JTable table) { TableModel tableModel = table.getModel(); TableColumnModel tableColumnModel = table.getColumnModel(); for (int i = 0; i < 4; i ++) { TableColumn tableColumn = tableColumnModel.getColumn(i); tableColumn.setCellRenderer(new CenteredRenderer()); } TableColumn tableColumn = tableColumnModel.getColumn(4); tableColumn.setCellEditor(new ButtonEditor(addButton)); tableColumn.setCellRenderer(new ButtonRenderer(addButton)); } private class CenteredRenderer extends JLabel implements TableCellRenderer { public CenteredRenderer() { super("", CENTER); this.setForeground(Color.black); } public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { setText((String)table.getModel().getValueAt(row, column)); return this; } } private class ButtonRenderer implements TableCellRenderer { private JButton button; private JLabel label; public ButtonRenderer(JButton b) { super(); // create a new button based on that passed in; use different button so clicks passed?? this.button = new JButton(b.getText()); this.label = new JLabel(""); } public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { //System.out.println("ButtonEditor.getTableCellRendererComponent"); HostInfo hostInfo = (HostInfo)hostInfoVector.elementAt(row); if (hostInfo.known) { return this.label; } else { return this.button; } } } private class ButtonEditor extends DefaultCellEditor { private JButton button; private JLabel label; public ButtonEditor(JButton b) { // constructor expects a check box, combo box, or text field super(new JCheckBox()); //System.out.println("ButtonEditor constructor"); // assign button as editor component button = b; label = new JLabel(""); setClickCountToStart(1); // do this so that editing stops when button clicked... b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //System.out.println("ButtonEditor: button clicked"); fireEditingStopped(); } }); } protected void fireEditingStopped() { //System.out.println("ButtonEditor.fireEditingStopped"); super.fireEditingStopped(); } public boolean shouldSelectCell(EventObject anEvent) { // return false so row not selected when button clicked... return false; } public Object getCellEditorValue() { //System.out.println("ButtonEditor.getCellEditorValue"); return null; } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { //System.out.println("ButtonEditor.getTableCellEditorComponent"); HostInfo hostInfo = (HostInfo)hostInfoVector.elementAt(row); if (hostInfo.known) { return this.label; } else { if (button instanceof JDataButton) { // set data in JDataButton so we know which entry to add JDataButton dataButton = (JDataButton)button; dataButton.setData(hostInfo.macAddress); } return this.button; } } } private String timeString(int time) { if (time < 0) return "unknown"; int seconds = time % 60; int minutes = (time /60) % 60; int hours = (time / 3600) % 24; int days = (time / 86400); String returnString = new String(); if (seconds == 1) returnString = seconds + " second"; else returnString = seconds + " seconds"; if (minutes > 0) { if (minutes == 1) returnString = minutes + " minute, " + returnString; else returnString = minutes + " minutes, " + returnString; } if (hours > 0) { if (hours == 1) returnString = hours + " hour, " + returnString; else returnString = hours + " hours, " + returnString; } if (days > 0) { if (days == 1) returnString = days + " day, " + returnString; else returnString = days + " days, " + returnString; } return returnString; } }hostmon-2.1/HostInfoChangeListener.java0000644000175000017500000000204007741514221017610 0ustar julienjulien/* * Wireless Host Monitor * * 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 HostInfoChangeListener { // do whatever in response to a change in the retrieved info public void processHostInfoChange(HostInfoTreeMap oldInfo, HostInfoTreeMap newInfo) throws HostInfoChangeException; }hostmon-2.1/AirportInfoRecord.java0000644000175000017500000003712207734713035016655 0ustar julienjulien/* * Wireless Host Monitor * * 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; } }hostmon-2.1/ValueFormatException.java0000644000175000017500000000224207734713670017366 0ustar julienjulien/* * Wireless Host Monitor * * 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); } }hostmon-2.1/JTextAreaWriter.java0000644000175000017500000000300607743371106016277 0ustar julienjulien/* * IPInspector * * Copyright (C) 2002, 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); } }hostmon-2.1/KnownHostInfo.java0000644000175000017500000000217407734713533016032 0ustar julienjulien/* * Wireless Host Monitor * * 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.io.*; public class KnownHostInfo implements Serializable { public MacAddress macAddress; public String name; public KnownHostInfo(String name, MacAddress macAddress) { this.name = name; this.macAddress = macAddress; } }hostmon-2.1/MacAddress.java0000644000175000017500000001120507734713556015272 0ustar julienjulien/* * Wireless Host Monitor * * 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.io.*; public class MacAddress implements Comparable, Serializable { private byte[] macAddress; public MacAddress(byte[] address) { macAddress = address; } public MacAddress(String macAddressString) throws ValueFormatException { this.macAddress = parseMacAddress(macAddressString); } private byte[] parseMacAddress(String addressString) throws ValueFormatException { 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 ValueFormatException("Wrong number of components supplied in MAC address"); } 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 ValueFormatException("Invalid characters used in MAC address"); returnBytes[i] = (byte)addressComponent; } return returnBytes; } catch (NumberFormatException e) { String messageString = "Invalid characters used in MAC address\n"; messageString += "MAC address must be specified as pairs of hex digits separated by spaces.\n"; messageString += " Example: 00 02 2d 37 1f a6"; throw new ValueFormatException(messageString); } catch (ValueFormatException e) { // augment the message string String messageString = e.getMessage() + "\n"; messageString += "MAC address must be specified as pairs of hex digits separated by spaces.\n"; messageString += " Example: 00 02 2d 37 1f a6"; throw new ValueFormatException(messageString); } } public boolean equals(Object other) { if (!(other instanceof MacAddress)) return false; MacAddress otherAddress = (MacAddress)other; if (macAddress.length != otherAddress.macAddress.length) return false; for (int i = 0; i < macAddress.length; i++) { if (this.macAddress[i] != otherAddress.macAddress[i]) return false; } // all address components equal; return true return true; } public int compareTo(Object other) { MacAddress otherAddress = (MacAddress)other; if (macAddress.length != otherAddress.macAddress.length) { if (macAddress.length < otherAddress.macAddress.length) return -1; else return 1; } for (int i = 0; i < macAddress.length; i++) { int unsigned = this.macAddress[i]; if (unsigned < 0) unsigned += 256; int otherUnsigned = otherAddress.macAddress[i]; if (otherUnsigned < 0) otherUnsigned += 256; if (unsigned < otherUnsigned) return -1; else if (unsigned > otherUnsigned) return 1; } // if get to here, they're equal return 0; } 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 */ public String toString() { String returnString = new String(); for (int i = 0; i < macAddress.length; i++) { returnString += hexByte(macAddress[i]) + " "; } return returnString; } }hostmon-2.1/KnownHostDialog.java0000644000175000017500000000765107734713523016342 0ustar julienjulien/* * Wireless Host Monitor * * 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.util.*; /** * Frame which presents data pertaining to modem login info. */ public class KnownHostDialog extends JDialog implements ActionListener { private TreeMap knownHostTreeMap; private KnownHostTable knownHostTable; private JButton okButton, cancelButton; private boolean isCanceled = false; public KnownHostDialog(Frame owner, TreeMap knownHostTreeMap) { super(owner, "Known Hosts", true /*modal*/); // close only on Cancel or OK button press this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.knownHostTreeMap = knownHostTreeMap; knownHostTable = new KnownHostTable(knownHostTreeMap); setUpDisplay(); } public void setUpDisplay() { okButton = new JButton("OK"); okButton.setActionCommand("ok"); okButton.addActionListener(this); cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(this); this.getRootPane().setDefaultButton(okButton); // set params for layout manager GridBagLayout theLayout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.fill = GridBagConstraints.NONE; c.ipadx = 0; c.ipady = 0; c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.CENTER; c.weightx = .5; c.weighty = .5; this.getContentPane().setLayout(theLayout); // add components c.gridwidth = 2; c.gridx = 1; c.gridy = 1; theLayout.setConstraints(knownHostTable, c); this.getContentPane().add(knownHostTable); c.gridwidth = 1; c.gridx = 1; c.gridy = 2; theLayout.setConstraints(okButton, c); this.getContentPane().add(okButton); c.gridx = 2; c.gridy = 2; theLayout.setConstraints(cancelButton, c); this.getContentPane().add(cancelButton); } public void actionPerformed(ActionEvent theEvent) // respond to button pushes { String command = theEvent.getActionCommand(); if (command.equals("ok")) { this.isCanceled = false; try { // set known host vector to that returned by table, if no errors this.knownHostTreeMap = knownHostTable.getKnownHostTreeMap(); this.setVisible(false); this.dispose(); } catch (ValueFormatException ve) { String messageString = "Problem with supplied value: " + ve.getMessage() + "\n"; JOptionPane.showMessageDialog(this, messageString, "Problem with input", JOptionPane.ERROR_MESSAGE); } } if (command.equals("cancel")) { this.isCanceled = true; this.setVisible(false); this.dispose(); } } public boolean isCanceled() { return this.isCanceled; } public void addHost(KnownHostInfo knownHostInfo) { knownHostTable.addHost(knownHostInfo); } public TreeMap getKnownHostTreeMap() { return this.knownHostTreeMap; } }hostmon-2.1/KnownHostTable.java0000644000175000017500000001657207734713544016177 0ustar julienjulien/* * Wireless Host Monitor * * 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 KnownHostTable extends JPanel { private Vector displayVector; private JTable table; private AbstractTableModel tableModel; private JScrollPane scrollPane; /** * Table model which maintains list of name - mac address pairs. */ private class KnownHostTableModel extends AbstractTableModel { public int getColumnCount() { return 2; } public int getRowCount() { return displayVector.size() + 1; } public boolean isCellEditable(int row, int col) { // allow first empty row to be editted if (row <= displayVector.size()) return true; else return false; } public String getColumnName(int col) { switch (col) { case 0: return "Name"; case 1: return "MAC address"; default: return ""; } } public Object getValueAt(int row, int col) { if (row < displayVector.size()) { String[] hostInfo = (String[])displayVector.elementAt(row); switch (col) { case 0: return hostInfo[0]; // name case 1: return hostInfo[1]; // MAC address default: return ""; } } else return ""; } public void setValueAt(Object newValue, int row, int col) { // do nothing if row is bigger than vector size if (row > displayVector.size()) return; if (newValue instanceof String) { if (row < displayVector.size()) { String[] hostInfo = (String[])displayVector.elementAt(row); hostInfo[col] = (String)newValue; } else { String[] hostInfo = {"",""}; hostInfo[col] = (String)newValue; displayVector.insertElementAt(hostInfo, displayVector.size()); } } } } /** * Create new empty table */ public KnownHostTable() { displayVector = new Vector(); table = new JTable(); tableModel = new KnownHostTableModel(); table.setModel(tableModel); table.setPreferredScrollableViewportSize(new Dimension(300,300)); scrollPane = new JScrollPane(table); setUpDisplay(); } /** * Create new table based on data in config file. */ public KnownHostTable(TreeMap knownHostTreeMap) { displayVector = new Vector(); Collection knownHostCollection = knownHostTreeMap.values(); Iterator iterator = knownHostCollection.iterator(); while (iterator.hasNext()) { KnownHostInfo knownHostInfo = (KnownHostInfo)iterator.next(); String[] hostInfo = {knownHostInfo.name, knownHostInfo.macAddress.toString()}; displayVector.add(hostInfo); } table = new JTable(); tableModel = new KnownHostTableModel(); table.setModel(tableModel); table.setPreferredScrollableViewportSize(new Dimension(300,300)); 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(Vector knownHostVector) { displayVector = new Vector(); for (int i = 0; i < knownHostVector.size(); i++) { KnownHostInfo knownHostInfo = (KnownHostInfo)knownHostVector.elementAt(i); String[] hostInfo = {knownHostInfo.name, knownHostInfo.macAddress.toString()}; displayVector.add(hostInfo); } tableModel.fireTableDataChanged(); } public synchronized void addHost(KnownHostInfo knownHostInfo) { String newMacAddressString = knownHostInfo.macAddress.toString().trim(); String newName = knownHostInfo.name; // see if MAC address already in list for (int i = 0; i < displayVector.size(); i++) { String[] hostInfo = (String[])displayVector.elementAt(i); String name = hostInfo[0]; String macAddressString = hostInfo[1].trim(); // if MAC address equals that we're adding, return if (macAddressString.equals(newMacAddressString)) return; } // didn't find it; add new info to table String[] newHostInfo = {newName, newMacAddressString}; displayVector.add(newHostInfo); tableModel.fireTableDataChanged(); } public synchronized TreeMap getKnownHostTreeMap() throws ValueFormatException { // stop any in-progress editing operations // first, record changes if cell currently being edited TableCellEditor editor = table.getCellEditor(); if(editor != null) editor.stopCellEditing(); // try to create a Vector of KnownHostInfo objects; this could throw // a ValueFormatException if there's an invalid MAC address TreeMap knownHostTreeMap = new TreeMap(); int i = 0; try { for (i = 0; i < displayVector.size(); i++) { String[] hostInfo = (String[])displayVector.elementAt(i); String name = hostInfo[0]; String macAddressString = hostInfo[1].trim(); // if MAC address string is empty after trimming, just continue if (macAddressString.equals("")) continue; MacAddress macAddress = new MacAddress(macAddressString); // throw exception if duplicate entry if (knownHostTreeMap.containsKey(macAddress)) throw new ValueFormatException("Duplicate entry for MAC address " + hostInfo[1]); knownHostTreeMap.put(macAddress, new KnownHostInfo(name, macAddress)); } } catch(ValueFormatException e) { // set the editing to the mac address in the row that caused the problem table.editCellAt(i,1); // rethrow the exception so can report it throw e; } return knownHostTreeMap; } 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); } } }hostmon-2.1/ArpInfo.java0000644000175000017500000000240007734713057014613 0ustar julienjulien/* * Wireless Host Monitor * * 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 MacAddress macAddress; public ArpInfo(String ipAddress, MacAddress macAddress) { this.ipAddress = ipAddress; this.macAddress = macAddress; } public String toString() { String returnValue = new String(); returnValue += ipAddress + " : " + macAddress.toString(); return returnValue; } }hostmon-2.1/ArpInfoTreeMap.java0000644000175000017500000000506307734713364016102 0ustar julienjulien/* * Wireless Host Monitor * * 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 HostInfo objects super(); for (int i = 0; i < varBindList.size(); i += 2) { SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPOctetString snmpMacAddress = (SNMPOctetString)variablePair.getSNMPObjectAt(1); MacAddress macAddress = new MacAddress((byte[])snmpMacAddress.getValue()); if ( (i+1) >= varBindList.size() ) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i+1); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPIPAddress snmpValue = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); String ipAddress = snmpValue.toString(); ArpInfo arpInfo = new ArpInfo(ipAddress, macAddress); // add new ArpInfo object to hashtable this.put(ipAddress, arpInfo); } } 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; } }hostmon-2.1/RarpInfoTreeMap.java0000644000175000017500000000514007734713617016261 0ustar julienjulien/* * Wireless Host Monitor * * 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 RarpInfoTreeMap extends TreeMap { public RarpInfoTreeMap() { // create empty Hashtable super(); } public RarpInfoTreeMap(SNMPVarBindList varBindList) { // create and populate Hashtable of HostInfo objects super(); for (int i = 0; i < varBindList.size(); i += 2) { SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPOctetString snmpMacAddress = (SNMPOctetString)variablePair.getSNMPObjectAt(1); MacAddress macAddress = new MacAddress((byte[])snmpMacAddress.getValue()); if ( (i+1) >= varBindList.size() ) break; variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i+1); snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPIPAddress snmpValue = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); String ipAddress = snmpValue.toString(); ArpInfo arpInfo = new ArpInfo(ipAddress, macAddress); // add new ArpInfo object to hashtable - it's RARP, so index by MAC address this.put(macAddress, arpInfo); } } 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; } }hostmon-2.1/HostInfoRetriever.java0000644000175000017500000000466407735162252016710 0ustar julienjulien/* * Wireless Host Monitor * * 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 snmp.*; import java.io.*; import java.util.*; public abstract class HostInfoRetriever { private static TreeMap hostInfoRetrievers = new TreeMap(); private static String name; /** * Load all known retrievers */ static { Class retrieverClass; String[] retrieverClassNames = {"AirportExtremeHostInfoRetriever", "SnowAirportHostInfoRetriever", "GraphiteAirportHostInfoRetriever"}; for (int i = 0; i < retrieverClassNames.length; i++) { try { retrieverClass = Class.forName(retrieverClassNames[i]); } catch (ClassNotFoundException e) { System.out.println("Class not found: " + retrieverClassNames[i]); } } } protected static void registerRetriever(String name, HostInfoRetriever newRetriever) { // just add this to retrievers vector hostInfoRetrievers.put(name, newRetriever); //System.out.println("Added a retriever: " + name); } public static TreeMap getRetrievers() { return hostInfoRetrievers; } public static HostInfoRetriever getRetriever(String name) { return (HostInfoRetriever)hostInfoRetrievers.get(name); } public static String getName() { return name; } public abstract int getWANInterfaceIndex(); public abstract HostInfoTreeMap getHostInfo(SNMPv1CommunicationInterface communicationInterface) throws IOException, SNMPGetException, SNMPBadValueException; }hostmon-2.1/AirportExtremeHostInfoRetriever.java0000644000175000017500000000502107735200325021561 0ustar julienjulien/* * Wireless Host Monitor * * 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 snmp.*; import java.io.*; public class AirportExtremeHostInfoRetriever extends HostInfoRetriever { // OIDs for retrieving info from Extreme base stations private static String macAddressBaseOID = "1.3.6.1.4.1.63.501.3.2.2.1.1"; private static String timeAssociatedBaseOID = "1.3.6.1.4.1.63.501.3.2.2.1.4"; private static String name = "Airport Extreme"; /** * Static initializer, to call base class routine registerRetriever with a name * to register this retriever in the list of retrievers when class is loaded */ static { AirportExtremeHostInfoRetriever retriever = new AirportExtremeHostInfoRetriever(); registerRetriever(name, retriever); } public int getWANInterfaceIndex() { // WAN interface is on index 2 for Extreme models return 2; } public HostInfoTreeMap getHostInfo(SNMPv1CommunicationInterface communicationInterface) throws IOException, SNMPGetException, SNMPBadValueException { // fetch associated host info String[] baseOIDs = {macAddressBaseOID, timeAssociatedBaseOID}; SNMPVarBindList snmpHostInfoTable = communicationInterface.retrieveMIBTable(baseOIDs); HostInfoTreeMap hostInfoHashtable = new HostInfoTreeMap(snmpHostInfoTable); //System.out.println("SNMP table:"); //System.out.println(snmpPortMapInfo.toString()); // now fetch arp info table, to get IP addresses String[] arpBaseOIDs = {"1.3.6.1.2.1.4.22.1.2", "1.3.6.1.2.1.4.22.1.3"}; SNMPVarBindList snmpArpInfo = communicationInterface.retrieveMIBTable(arpBaseOIDs); RarpInfoTreeMap rarpInfoTreeMap = new RarpInfoTreeMap(snmpArpInfo); hostInfoHashtable.setIPAddresses(rarpInfoTreeMap); return hostInfoHashtable; } }hostmon-2.1/SnowAirportHostInfoRetriever.java0000644000175000017500000000620607735162143021111 0ustar julienjulien/* * Wireless Host Monitor * * 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 snmp.*; import java.io.*; import java.util.*; public class SnowAirportHostInfoRetriever extends HostInfoRetriever { // OIDs for retrieving info from Snow base stations private String portMapLocalIPBaseOID = "1.3.6.1.4.1.731.100.3.1.1.2"; private static String name = "Airport (Snow)"; private static SnowAirportHostInfoRetriever retriever = new SnowAirportHostInfoRetriever(); /** * Static initializer, to call base class routine registerRetriever to * register this retriever in the list of retrievers when class is loaded */ static { registerRetriever(name, retriever); } public int getWANInterfaceIndex() { // WAN interface is on index 3 return 3; } public HostInfoTreeMap getHostInfo(SNMPv1CommunicationInterface communicationInterface) throws IOException, SNMPGetException, SNMPBadValueException { // fetch portmap info - local IPs SNMPVarBindList varBindList = communicationInterface.retrieveMIBTable(portMapLocalIPBaseOID); // create a TreeMap to filter out duplicates TreeMap ipAddressTreeMap = new TreeMap(); for (int i = 0; i < varBindList.size(); i++) { SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPIPAddress snmpIPAddress = (SNMPIPAddress)variablePair.getSNMPObjectAt(1); String ipAddress = snmpIPAddress.toString(); if (!ipAddressTreeMap.containsKey(ipAddress)) { HostInfo hostInfo = new HostInfo(); hostInfo.ipAddress = ipAddress; hostInfo.timeAssociated = -1; ipAddressTreeMap.put(ipAddress, hostInfo); } } // now create host info hashtable from this tree map HostInfoTreeMap hostInfoHashtable = new HostInfoTreeMap(ipAddressTreeMap); //System.out.println("SNMP table:"); //System.out.println(snmpPortMapInfo.toString()); // now fetch arp info table, to get MAC addresses String[] arpBaseOIDs = {"1.3.6.1.2.1.4.22.1.2", "1.3.6.1.2.1.4.22.1.3"}; SNMPVarBindList snmpArpInfo = communicationInterface.retrieveMIBTable(arpBaseOIDs); ArpInfoTreeMap arpInfoTreeMap = new ArpInfoTreeMap(snmpArpInfo); hostInfoHashtable.setMACAddresses(arpInfoTreeMap); return hostInfoHashtable; } }hostmon-2.1/GraphiteAirportHostInfoRetriever.java0000644000175000017500000000762707735415233021737 0ustar julienjulien/* * Wireless Host Monitor * * 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 snmp.*; import java.io.*; public class GraphiteAirportHostInfoRetriever extends HostInfoRetriever { // OIDs for retrieving info from Graphite base stations private static String macAddressBaseOID = "1.3.6.1.4.1.762.2.5.2.1.11"; private static String ipAddressBaseOID = "1.3.6.1.4.1.762.2.5.2.1.15"; private static String name = "Airport (Graphite) / RG-1000"; /** * Static initializer, to call base class routine registerRetriever with a name * to register this retriever in the list of retrievers when class is loaded */ static { GraphiteAirportHostInfoRetriever retriever = new GraphiteAirportHostInfoRetriever(); registerRetriever(name, retriever); } public int getWANInterfaceIndex() { // Ethernet interface is on index 1; unfortunately, the ipAddress table lists _all_ of the interfaces // as interface 1, so the first listed IP address is what we'll get, and that seems to generally be // the one corresponding to the LAN (wireless) interface. return 1; } public HostInfoTreeMap getHostInfo(SNMPv1CommunicationInterface communicationInterface) throws IOException, SNMPGetException, SNMPBadValueException { // do wireless host discovery process String itemID; SNMPVarBindList newVars; SNMPSequence pair; SNMPInteger snmpIntegerValue; SNMPObject snmpValue; // first, need to write values to appropriate OID's - why, I don't know... try { for (int i = 1; i <= 3; i++) { itemID = "1.3.6.1.4.1.762.2.5.5." + i; communicationInterface.setMIBEntry(itemID, new SNMPInteger(500)); // was 50 itemID = "1.3.6.1.4.1.762.2.5.4." + i; communicationInterface.setMIBEntry(itemID, new SNMPInteger(3)); } } catch (SNMPSetException e) { throw new SNMPGetException("Unable to configure base station to retrieve information"); } String[] baseOIDs = {macAddressBaseOID}; SNMPVarBindList varBindList = communicationInterface.retrieveMIBTable(baseOIDs); // create a Vector with HostInfo HostInfoTreeMap hostInfoTreeMap = new HostInfoTreeMap(); for (int i = 0; i < varBindList.size(); i++) { SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0); SNMPOctetString snmpMacAddress = (SNMPOctetString)variablePair.getSNMPObjectAt(1); MacAddress macAddress = new MacAddress((byte[])snmpMacAddress.getValue()); HostInfo hostInfo = new HostInfo(); hostInfo.macAddress = macAddress; hostInfo.timeAssociated = -1; hostInfoTreeMap.put(macAddress, hostInfo); } // now fetch arp info table, to get IP addresses String[] arpBaseOIDs = {"1.3.6.1.2.1.4.22.1.2", "1.3.6.1.2.1.4.22.1.3"}; SNMPVarBindList snmpArpInfo = communicationInterface.retrieveMIBTable(arpBaseOIDs); RarpInfoTreeMap rarpInfoTreeMap = new RarpInfoTreeMap(snmpArpInfo); hostInfoTreeMap.setIPAddresses(rarpInfoTreeMap); return hostInfoTreeMap; } }hostmon-2.1/JDataButton.java0000644000175000017500000000241107734713500015427 0ustar julienjulien/* * Wireless Host Monitor * * 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 javax.swing.*; public class JDataButton extends JButton { private Object data; public JDataButton(String text, Object data) { super(text); this.data = data; } public JDataButton(String text) { super(text); this.data = null; } public void setData(Object data) { this.data = data; } public Object getData() { return this.data; } }hostmon-2.1/HostInfoLogger.java0000644000175000017500000001133507742657051016155 0ustar julienjulien/* * Wireless Host Monitor * * 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.util.*; public class HostInfoLogger implements HostInfoChangeListener { String logFile; int logMode; public HostInfoLogger(String logFile, int logMode) { this.logFile = logFile; this.logMode = logMode; } // do whatever in response to a change in the retrieved info public void processHostInfoChange(HostInfoTreeMap oldInfo, HostInfoTreeMap newInfo) throws HostInfoChangeException { try { switch (logMode) { case Preferences2.LOG_ALL: case Preferences2.LOG_UNKNOWN: { // log any hosts that are in the new info and not in the old // open file for writing; will throw exception if problem with that... FileWriter fileWriter = new FileWriter(logFile, true /*append*/); Iterator iterator = newInfo.keySet().iterator(); while(iterator.hasNext()) { Object key = iterator.next(); //System.out.println("Processing key " + key); if (oldInfo.containsKey(key)) { // we already know about this guy; continue //System.out.println("Got this host already"); continue; } // a new arrival; get info HostInfo newHostInfo = (HostInfo)newInfo.get(key); // if log mode is LOG_UNKNOWN, log only hosts that are unknown if ((logMode == Preferences2.LOG_UNKNOWN) && (newHostInfo.known == true)) { // we know this guy; continue //System.out.println("Known host"); continue; } //System.out.println("Writing new info"); // write info out to file String hostInfoString = (new Date()).toString(); if (newHostInfo.known == true) hostInfoString += ": " + newHostInfo.name + ", MAC address " + newHostInfo.macAddress; else hostInfoString += ": Unknown host, MAC address " + newHostInfo.macAddress; hostInfoString += ", IP address " + newHostInfo.ipAddress; if (newHostInfo.timeAssociated < 0) hostInfoString += ", time associated unknown\n"; else hostInfoString += ", time associated " + newHostInfo.timeAssociated + ".\n"; fileWriter.write(hostInfoString); } fileWriter.flush(); fileWriter.close(); break; } case Preferences2.LOG_NONE: default: { // pretty boring choice, n'est-ce pas? break; } } } catch (Exception e) { throw new HostInfoChangeException(e.toString()); } } public void setLogFile(String logFile) { this.logFile = logFile; } public void setLogMode(int logMode) { this.logMode = logMode; } }hostmon-2.1/HostInfoChangeException.java0000644000175000017500000000223107741514405017767 0ustar julienjulien/* * Wireless Host Monitor * * 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 by HostInfoChangeListener interface to report problems when processing change in host info */ public class HostInfoChangeException extends Exception { /** * Construct new exception with specified error message. */ public HostInfoChangeException(String specifics) { super(specifics); } }hostmon-2.1/Preferences2.java0000644000175000017500000001013607743113310015567 0ustar julienjulien/* * Wireless Host Monitor * * 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 Preferences2 extends Preferences implements Serializable { public boolean logFlag; public int logMode; public String logFile; public boolean notifyFlag; public int notifyMode; public boolean beepNotifyFlag; public boolean emailNotifyFlag; public String emailAddress; public String emailSMTPHost; public static final int LOG_ALL = 1; public static final int LOG_UNKNOWN = 2; public static final int LOG_NONE = 3; public static final int NOTIFY_ALL = 1; public static final int NOTIFY_UNKNOWN = 2; public static final int NOTIFY_NONE = 3; public Preferences2() { super(); logFlag = false; logMode = LOG_NONE; logFile = ""; notifyFlag = false; notifyMode = NOTIFY_NONE; beepNotifyFlag = false; emailNotifyFlag = false; emailAddress = ""; emailSMTPHost = ""; } public Preferences2(Preferences preferences) { this.ipAddress = preferences.ipAddress; this.password = preferences.password; this.queryInterval = preferences.queryInterval; this.accessPointType = preferences.accessPointType; logFlag = false; logMode = LOG_NONE; logFile = ""; notifyFlag = false; notifyMode = NOTIFY_NONE; beepNotifyFlag = false; emailNotifyFlag = false; emailAddress = ""; emailSMTPHost = ""; } public Preferences2(Preferences2 preferences) { this.ipAddress = preferences.ipAddress; this.password = preferences.password; this.queryInterval = preferences.queryInterval; this.accessPointType = preferences.accessPointType; this.logFlag = preferences.logFlag; this.logMode = preferences.logMode; this.logFile = preferences.logFile; this.notifyFlag = preferences.notifyFlag; this.notifyMode = preferences.notifyMode; this.beepNotifyFlag = preferences.beepNotifyFlag; this.emailNotifyFlag = preferences.emailNotifyFlag; this.emailAddress = preferences.emailAddress; this.emailSMTPHost = preferences.emailSMTPHost; } public boolean equals(Object otherPrefsObject) { if (!(otherPrefsObject instanceof Preferences2)) { return false; } Preferences2 otherPrefs = (Preferences2)otherPrefsObject; // check superclass fields if (!super.equals(otherPrefsObject)) return false; // compare all fields but passwords if ( (this.logFlag == otherPrefs.logFlag) && (this.logMode == otherPrefs.logMode) && (this.logFile.equals(otherPrefs.logFile)) && (this.notifyFlag == otherPrefs.notifyFlag) && (this.notifyMode == otherPrefs.notifyMode) && (this.beepNotifyFlag == otherPrefs.beepNotifyFlag) && (this.emailNotifyFlag == otherPrefs.emailNotifyFlag) && (this.emailAddress.equals(otherPrefs.emailAddress)) && (this.emailSMTPHost.equals(otherPrefs.emailSMTPHost)) ) { return true; } else { return false; } } }hostmon-2.1/InfoPanel.java0000644000175000017500000000310607742651340015127 0ustar julienjulien/* * Wireless Host Monitor * * 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.*; public class InfoPanel extends JPanel implements ItemListener { /** * Used to trigger this panel to be enabled or disabled, by registering it * as a ChangeListener with an AbstractButton instance. */ public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) this.setEnabled(true); else this.setEnabled(false); } /** * Enable and disable contained components. */ public void setEnabled(boolean enabled) { Component[] components = this.getComponents(); super.setEnabled(enabled); for (int i = 0; i < components.length; i++) components[i].setEnabled(enabled); } }hostmon-2.1/HostInfoBeepAlerter.java0000644000175000017500000000647507743123751017135 0ustar julienjulien/* * Wireless Host Monitor * * 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.util.*; import java.awt.Toolkit; public class HostInfoBeepAlerter implements HostInfoChangeListener { int notifyMode; public HostInfoBeepAlerter(int notifyMode) { this.notifyMode = notifyMode; } // beep in response to a change in the retrieved info public void processHostInfoChange(HostInfoTreeMap oldInfo, HostInfoTreeMap newInfo) throws HostInfoChangeException { try { switch (notifyMode) { case Preferences2.NOTIFY_ALL: case Preferences2.NOTIFY_UNKNOWN: { // beep for any hosts that are in the new info and not in the old Iterator iterator = newInfo.keySet().iterator(); while(iterator.hasNext()) { Object key = iterator.next(); //System.out.println("Processing key " + key); if (oldInfo.containsKey(key)) { // we already know about this guy; continue continue; } // a new arrival; get info HostInfo newHostInfo = (HostInfo)newInfo.get(key); // if mode is NOTIFY_UNKNOWN, beep only for hosts that are unknown if ((notifyMode == Preferences2.NOTIFY_UNKNOWN) && (newHostInfo.known == true)) { // we know this guy; continue continue; } // previously unseen host - beep! Toolkit.getDefaultToolkit().beep(); } break; } case Preferences2.NOTIFY_NONE: default: { // pretty boring choice, n'est-ce pas? break; } } } catch (Exception e) { throw new HostInfoChangeException(e.toString()); } } public void setNotifyMode(int notifyMode) { this.notifyMode = notifyMode; } }hostmon-2.1/HostInfoChangeEmailer.java0000644000175000017500000001204607743374352017423 0ustar julienjulien/* * IPInspector * * Copyright (C) 2002, 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.util.*; public class HostInfoChangeEmailer implements HostInfoChangeListener { String userEmailAddress; String mailHost; String baseStationName = ""; int notifyMode; Writer errorWriter; MailerThread mailerThread; public HostInfoChangeEmailer(String userEmailAddress, String mailHost, int notifyMode, Writer errorWriter) { this.userEmailAddress = userEmailAddress; this.mailHost = mailHost; this.baseStationName = baseStationName; this.notifyMode = notifyMode; this.errorWriter = errorWriter; } // do whatever in response to a change in the retrieved info public void processHostInfoChange(HostInfoTreeMap oldInfo, HostInfoTreeMap newInfo) throws HostInfoChangeException { String messageText = ""; // see if any new hosts have appeared switch (notifyMode) { case Preferences2.NOTIFY_ALL: case Preferences2.NOTIFY_UNKNOWN: { // send email for hosts that are in the new info and not in the old Iterator iterator = newInfo.keySet().iterator(); while(iterator.hasNext()) { Object key = iterator.next(); //System.out.println("Processing key " + key); if (oldInfo.containsKey(key)) { // we already know about this guy; continue continue; } // a new arrival; get info HostInfo newHostInfo = (HostInfo)newInfo.get(key); // if mode is NOTIFY_UNKNOWN, beep only for hosts that are unknown if ((notifyMode == Preferences2.NOTIFY_UNKNOWN) && (newHostInfo.known == true)) { // we know this guy; continue continue; } // previously unseen host - add to message if (newHostInfo.known == true) messageText += "Name: " + newHostInfo.name + "\r\n"; else messageText += "Name: Unknown host\r\n";; messageText += "MAC address: " + newHostInfo.macAddress + "\r\n"; messageText += "IP address: " + newHostInfo.ipAddress + "\r\n"; if (newHostInfo.timeAssociated < 0) messageText += "Time associated: unknown\r\n"; else messageText += "Time associated: " + newHostInfo.timeAssociated + "\r\n"; messageText += "\r\n"; } break; } case Preferences2.NOTIFY_NONE: default: { // pretty boring choice, n'est-ce pas? break; } } // see if have any hosts in message if (messageText.equals("")) { // no new hosts; return return; } // have new hosts; create message String messageHeader = "To: " + userEmailAddress + "\r\n"; messageHeader += "From: Airport base station (" + baseStationName + ")\r\n"; messageHeader += "Date: " + (new Date()).toString() + "\r\n"; messageHeader += "Subject: New host(s) associated with base station\r\n\r\n\r\n"; messageHeader += "Time: " + (new Date()).toString() + "\r\n"; messageHeader += "New host(s) associated with base station " + baseStationName + ":\r\n\r\n\r\n"; messageText = messageHeader + messageText; // start mailer thread mailerThread = new MailerThread(userEmailAddress, mailHost, messageText, errorWriter); mailerThread.start(); } public void setBaseStationName(String baseStationName) { this.baseStationName = baseStationName; } }hostmon-2.1/MailerThread.java0000644000175000017500000000471107743375200015617 0ustar julienjulien/* * IPInspector * * Copyright (C) 2002, 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.util.*; public class MailerThread extends Thread { String userEmailAddress; String mailHost; String messageText; POPWeasel mailman; Writer errorWriter; public MailerThread(String userEmailAddress, String mailHost, String messageText, Writer errorWriter) { this.userEmailAddress = userEmailAddress; this.mailHost = mailHost; this.messageText = messageText; this.errorWriter = errorWriter; mailman = new POPWeasel(); } public void run() { EmailMessage changeMessage = new EmailMessage(); changeMessage.recipients.add(userEmailAddress); changeMessage.text = messageText; try { mailman.sendMessage(userEmailAddress, mailHost, changeMessage); } catch (Exception e) { try { errorWriter.write("Error sending message: " + e.toString() + ", " + (new Date()).toString() + ".\n"); } catch (IOException ex) { // print to System out System.out.println("Error sending message: " + e.toString() + ", " + (new Date()).toString() + "."); } } try { errorWriter.write("Sent notification of change to " + userEmailAddress + ", " + (new Date()).toString() + ".\n"); } catch (IOException ex) { // print to System out System.out.println("Sent notification of change to " + userEmailAddress + ", " + (new Date()).toString() + "."); } } }hostmon-2.1/EmailMessage.java0000644000175000017500000000206607743367564015631 0ustar julienjulien/* * IPInspector * * Copyright (C) 2002, 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 * */ /* EmailMessage class Just a utility class */ import java.util.*; public class EmailMessage { public Vector recipients; public String text; public EmailMessage() { recipients = new Vector(); text = ""; } }hostmon-2.1/POPWeasel.java0000644000175000017500000002150307743370336015060 0ustar julienjulien/* * IPInspector * * Copyright (C) 2002, 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 * */ /* class POPWeasel Defines object that will communicate with POP and SMTP servers to get and send e-mail (pardon the name) Defines methods: public Vector getMessages(UserInfo user, String mailHost) Retrieves messages from specified POP host, using supplied user ID and password. Return as vector of Strings (one per message) public void sendMessages(UserInfo user, Vector messages, String mailHost) Send the messages corresponding to the Vector supplied of Message objects, using the specified SMTP host */ import java.util.*; import java.net.*; import java.io.*; public class POPWeasel { public static final int POPPORT = 110; public static final int SMTPPORT = 25; public static final boolean debug = false; public POPWeasel() { } public Vector getMessages(String userName, String password, String mailHost) throws Exception { Socket mailSocket; BufferedReader istream; BufferedWriter ostream; Vector messageList = new Vector(); mailSocket = new Socket(mailHost, POPWeasel.POPPORT); istream = new BufferedReader(new InputStreamReader(mailSocket.getInputStream())); ostream = new BufferedWriter(new OutputStreamWriter(mailSocket.getOutputStream())); establishPOPSession(userName, password, istream, ostream); messageList = retrieveMessages(istream, ostream); closePOPSession(istream, ostream); istream.close(); ostream.close(); mailSocket.close(); return messageList; } public void sendMessages(String userEmailAddress, String mailHost, Vector messages) throws Exception { Socket mailSocket; BufferedReader istream; BufferedWriter ostream; mailSocket = new Socket(mailHost, POPWeasel.SMTPPORT); istream = new BufferedReader(new InputStreamReader(mailSocket.getInputStream())); ostream = new BufferedWriter(new OutputStreamWriter(mailSocket.getOutputStream())); establishSMTPSession(mailHost, istream, ostream); sendMessages(userEmailAddress, messages, istream, ostream); closeSMTPSession(istream, ostream); istream.close(); ostream.close(); mailSocket.close(); return; } // Utility method for sending a single email message public void sendMessage(String userEmailAddress, String mailHost, EmailMessage message) throws Exception { Vector messageVector = new Vector(); messageVector.add(message); this.sendMessages(userEmailAddress, mailHost, messageVector); } private void checkPOPResponse(String response) throws IOException // utility method, to see if POP server sends happy response; throws a "fit" // (also known as an Exception) if response doesn't begin with "+OK" { StringTokenizer st; debugPrintln("Server: " + response); st = new StringTokenizer(response); if (!st.nextToken().equals("+OK")) throw new IOException(response); } private void establishPOPSession(String userName, String password, BufferedReader istream, BufferedWriter ostream) throws IOException // Send username and password to establish POP session { checkPOPResponse(istream.readLine()); ostream.write("USER " + userName); ostream.newLine(); ostream.flush(); debugPrintln("Client: USER " + userName); checkPOPResponse(istream.readLine()); ostream.write("PASS " + password); ostream.newLine(); ostream.flush(); debugPrintln("Client: PASS (hidden)"); checkPOPResponse(istream.readLine()); return; } private Vector retrieveMessages(BufferedReader istream, BufferedWriter ostream) throws IOException, NumberFormatException // Get waiting messages, sending STAT and RETR messages to POP host { Vector retrievedMessages = new Vector(); StringTokenizer st; String nextLine; String nextToken; int numMessages; ostream.write("STAT"); ostream.newLine(); ostream.flush(); debugPrintln("Client: STAT"); nextLine = istream.readLine(); debugPrintln("Server: " + nextLine); st = new StringTokenizer(nextLine); if (!st.nextToken().equals("+OK")) throw new IOException(nextLine); nextToken = st.nextToken(); // will be number of messages to retrieve numMessages = Integer.parseInt(nextToken); for (int i=1; i <= numMessages; ++i) { // get waiting messages String newMessage = new String(); ostream.write("RETR " + i) ; ostream.newLine(); ostream.flush(); debugPrintln("Client: RETR " + i); checkPOPResponse(istream.readLine()); while (!(nextLine = istream.readLine()).equals(".")) { // add each line of message to message string newMessage += nextLine + "\n"; } // add message to vector to be returned retrievedMessages.insertElementAt(newMessage, retrievedMessages.size()); } return retrievedMessages; } private void closePOPSession(BufferedReader istream, BufferedWriter ostream) throws IOException { ostream.write("QUIT"); ostream.newLine(); ostream.flush(); } private void checkSMTPResponse(String response, String expected) throws IOException // See if SMTP host returns string expected at current stage of communication; // if not, throw a fit (exception) { StringTokenizer st; debugPrintln("Server: " + response); st = new StringTokenizer(response); if (!st.nextToken().equals(expected)) throw new IOException(response); } private void establishSMTPSession(String domainName, BufferedReader istream, BufferedWriter ostream) throws IOException { checkSMTPResponse(istream.readLine(), "220"); ostream.write("HELO " + domainName); //ostream.newLine(); ostream.write("\r\n"); ostream.flush(); debugPrintln("Client: HELO " + domainName); checkSMTPResponse(istream.readLine(), "250"); return; } private void sendMessages(String userEmailAddress, Vector messages, BufferedReader istream, BufferedWriter ostream) throws IOException { Enumeration e = messages.elements(); while (e.hasMoreElements()) { // send next message EmailMessage m = (EmailMessage)e.nextElement(); //try //{ ostream.write("MAIL FROM:" + "<" + userEmailAddress + ">"); //ostream.newLine(); ostream.write("\r\n"); ostream.flush(); debugPrintln("Client: MAIL FROM:" + "<" + userEmailAddress + ">"); checkSMTPResponse(istream.readLine(), "250"); Enumeration addresses = (m.recipients).elements(); while(addresses.hasMoreElements()) { String recipient = (String)addresses.nextElement(); ostream.write("RCPT TO:" + "<" + recipient + ">"); //ostream.newLine(); ostream.write("\r\n"); ostream.flush(); debugPrintln("Client: RCPT TO:" + "<" + recipient + ">"); checkSMTPResponse(istream.readLine(), "250"); } ostream.write("DATA"); //ostream.newLine(); ostream.write("\r\n"); ostream.flush(); debugPrintln("Client: DATA"); checkSMTPResponse(istream.readLine(), "354"); ostream.write(m.text); //ostream.newLine(); ostream.write("\r\n"); //ostream.flush(); debugPrintln("Message text sent"); ostream.write("."); // CR-LF = 0x0D 0x0A = octal 015 012 //ostream.newLine(); ostream.write("\r\n"); //ostream.newLine(); ostream.flush(); //debugPrintln("."); checkSMTPResponse(istream.readLine(), "250"); //} //catch (Exception except) //{ // debugPrintln("Problem sending email message: " + except); //} } return; } private void closeSMTPSession(BufferedReader istream, BufferedWriter ostream) throws IOException { ostream.write("QUIT"); //ostream.newLine(); ostream.write("\r\n"); ostream.flush(); debugPrintln("Client: QUIT"); } private void debugPrintln(String message) { if (this.debug) System.out.println(message); } }