package org.openslx.dozmod.gui.configurator;
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import org.apache.log4j.Logger;
import org.openslx.bwlp.thrift.iface.NetDirection;
import org.openslx.bwlp.thrift.iface.NetRule;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.changemonitor.GenericControlWindow;
import org.openslx.dozmod.gui.control.WordWrapLabel;
import org.openslx.dozmod.gui.helper.GridManager;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.helper.TextChangeListener;
import org.openslx.util.Util;
/**
* Widget for netrules configuration of lectures
*/
public class NetrulesConfigurator extends NetrulesConfiguratorLayout implements GenericControlWindow<List<NetRule>> {
private static final long serialVersionUID = -3497629601818983994L;
private final static Logger LOGGER = Logger.getLogger(NetrulesConfigurator.class);
private boolean checkChange = false;
private List<NetRule> currentState;
private List<ChangeListener> listeners;
/**
* Character defining how the rules are parsed, e.g. for whitespace \\s
* Example: "8.8.8.8 80 in" would be split in -hostname "8.8.8.8" -port "80"
* -direction "in"
*/
private static final String FIELD_DELIMITER = "\\s+";
private static final Color FOREGROUND_TEXT_COLOR;
static {
Color fgOrigColor = UIManager.getDefaults().getColor("ColorChooser.foreground");
if (fgOrigColor == null) {
// use black as fallback
fgOrigColor = Color.BLACK;
}
FOREGROUND_TEXT_COLOR = fgOrigColor;
}
public NetrulesConfigurator() {
super();
final TextChangeListener docListener = new TextChangeListener() {
@Override
public void changed() {
checkChange = true;
}
};
final SimpleAttributeSet as = new SimpleAttributeSet();
StyleConstants.setForeground(as, FOREGROUND_TEXT_COLOR);
tpNetworkRules.getDocument().addDocumentListener(docListener);
tpNetworkRules.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int pos = tpNetworkRules.getCaretPosition();
if (pos < 0) {
return;
}
// Odd: On windows, getText() returns the text with CRLF line breaks,
// regardless of what you put into the text box.
// The offsets passed to setCharAttrs() below and the caret position
// you get from getCaretPosition() however have to adhere to the
// text version with just LF, exactly how we created the document.
String text = tpNetworkRules.getText().replace("\r", "");
if (pos >= text.length()) {
return;
}
int start = text.lastIndexOf('\n', pos == 0 ? 0 : pos - 1);
int end = text.indexOf('\n', pos);
if (start == -1) {
start = 0;
}
if (end == -1) {
end = text.length() - 1;
}
if (end <= start) {
return;
}
tpNetworkRules.getStyledDocument().setCharacterAttributes(start, end - start, as, true);
}
});
}
});
tpNetworkRules.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (checkChange) {
fireChangeEvent();
}
}
});
}
/**
* Gets the state of the widget as a list of netrules. Internally it first
* transforms the input text in a list of netrules.
*
* @return the list of rules as parsed by parseNetRules()
*/
@Override
public List<NetRule> getState() {
return getState(true);
}
public List<NetRule> getState(boolean silent) {
if (checkChange || !silent) {
currentState = parseNetRules(silent);
}
return currentState;
}
@Override
public void addChangeListener(ChangeListener l) {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(l);
}
private void fireChangeEvent() {
if (listeners == null)
return;
for (ChangeListener cl : listeners) {
cl.stateChanged(null);
}
}
/**
* Sets the state of this widget to the given list of netrules. This will
* internally transform the list to its string representation
*
* @param netrules
* as a list of NetRule to set the state to
*/
public void setState(final List<NetRule> netrules) {
checkChange = true;
currentState = netrules;
this.tpNetworkRules.setText(decodeNetRulesToText(netrules));
fireChangeEvent();
}
/**
* "Decodes" the given list of NetRule to a single String. This should be
* used to set the text in the TextPane for the network rules
*
* @param netRulesList
* list of NetRule to decode
* @return String representation of the list of rules
*/
public static String decodeNetRulesToText(final List<NetRule> netRulesList) {
if (netRulesList == null || netRulesList.isEmpty())
return "";
String decodedRules = "";
Iterator<NetRule> it = netRulesList.iterator();
while (it.hasNext()) {
String currentLine = "";
NetRule currentRule = it.next();
// simple test for validity (since this comes from the server it
// should be correct anyways)
if (currentRule.host.isEmpty() || currentRule.port > 65535) {
LOGGER.error("Invalid rule! Ignoring: " + currentRule.host
+ ":" + currentRule.port);
continue;
}
currentLine += currentRule.host + " \t ";
currentLine += currentRule.port + " \t ";
currentLine += currentRule.direction.name();
decodedRules += currentLine
+ (it.hasNext() ? "\n" : "");
}
return decodedRules;
}
/**
* Parses the given rawNetRules String to a list of NetRule
*
* @param rawNetRules
* the raw text to be parsed
* @return list of netrules if successful. If any errors occured while
* parsing, null is returned.
*/
public List<NetRule> parseNetRules(boolean silent) {
String rawNetRules = tpNetworkRules.getText().trim();
List<NetRule> rulesList = new ArrayList<NetRule>();
if (rawNetRules.isEmpty()) {
return rulesList;
}
// split it line by line
boolean invalid = false; // True if the rules are invalid and null should be returned
DefaultStyledDocument newdoc = null;
if (!silent) {
newdoc = new DefaultStyledDocument(); // Used to build new document with colors
}
StringBuilder errors = new StringBuilder(); // Error messages to show (if not silent)
int lineNo = 0; // Show line numbers in error messages
Set<String> warnedHosts = new HashSet<>(); // Ask only once about each unknown host
for (String ruleLine : rawNetRules.split("[\r\n]+")) {
if (silent && invalid)
return null;
Color lineColor = null;
LOGGER.debug("Parsing rule: " + ruleLine);
// split the fields and check if we have 3 as expected.
String[] fields = ruleLine.trim().split(FIELD_DELIMITER);
if (fields.length != 3) {
lineNo += addLine(newdoc, ruleLine, Color.RED, true);
// log numbers for fields independently...
LOGGER.debug("Invalid number of fields! Expected 3, got: " + fields.length);
if (fields.length > 3) {
errors.append("Zeile " + lineNo + ": Zu viele Felder.\n");
} else {
errors.append("Zeile " + lineNo + ": Zu wenig Felder.\n");
}
invalid = true;
continue;
}
// Have 3 fields, pretty up
String ruleDirection = fields[2].toUpperCase();
ruleLine = fields[0] + " \t " + fields[1] + " \t " + ruleDirection;
// start to check fields one by one from the last to the first ....
// check net direction: accept either 'in' or 'out' (case
// insensitive)
// TODO support combined 'in/out' rules
if (!ruleDirection.equals("IN") && !ruleDirection.equals("OUT")) {
lineNo += addLine(newdoc, ruleLine, Color.RED, true);
LOGGER.debug("Invalid net direction! Expected 'in' or out'. Got: " + ruleDirection);
errors.append("Zeile " + lineNo + ": Ungültige Richtung. Bitte nutzen Sie 'IN' bzw. 'OUT'.\n");
invalid = true;
continue;
}
// check port: accept if >= 0 and <= 65535
int port = Util.parseInt(fields[1], -1);
// port = 0 means match only host (all protocols and ports)
if (port < 0 || port > 65535) {
lineNo += addLine(newdoc, ruleLine, Color.RED, true);
LOGGER.debug("Invalid port! Got: " + port);
errors.append("Zeile " + lineNo + ": Ungültiger Port. Gültiger Bereich ist 0-65535.\n");
invalid = true;
continue;
}
// check hostname: bit more to do here
// for IPs and/or resolvable hostnames we make use of java.net's
// InetAddress.getByName() method which checks the validity of
// an IP-Address represented by a string or if the given hostname
// is resolvable. If any of these happen, we have a valid hostname.
// Non-resolvable hostnames are handled differently, see after the
// try/catch-block
InetAddress ruleHost = null;
try {
// TODO: Find a way to reliably set a timeout (external DNS library?)
// Otherwise just remove this check
ruleHost = InetAddress.getByName(fields[0]);
} catch (UnknownHostException e) {
// might be good to see this exception in the log file
// LOGGER.debug("Invalid hostname (java.net): ", e);
}
if (ruleHost == null) {
// either invalid IP-Address or an invalid resolvable hostname
// however it might also be a non-resolvable hostname that would
// be valid in the actual pool-rooms, so lets check its syntax
// according to: http://tools.ietf.org/html/rfc1034#section-3.1
LOGGER.debug("Invalid host/IP! Got: " + fields[0]);
String checkRes = checkHostnameSimple(fields[0]);
if (checkRes == null) {
if (!silent
&& !warnedHosts.contains(fields[0])
&& !Gui.showMessageBox("Konnte '" + fields[0]
+ "' nicht auflösen. Wollen Sie diesen Hostnamen trotzdem verwenden?",
MessageType.WARNING_RETRY, null, null)) {
invalid = true;
}
warnedHosts.add(fields[0]);
lineColor = Color.ORANGE;
} else {
lineNo += addLine(newdoc, ruleLine, Color.RED, true);
errors.append("Zeile " + lineNo + ": " + checkRes + "\n");
invalid = true;
continue;
}
}
// Made it to here - line is valid
lineNo += addLine(newdoc, ruleLine, lineColor, false);
rulesList.add(new NetRule(NetDirection.valueOf(ruleDirection), fields[0], port));
}
if (!silent && errors.length() != 0) {
Gui.showMessageBox("Fehler beim Auswerten der angegebenen Netzwerkregeln.\n\n" + errors.toString()
+ "\nBitte geben Sie die Regeln zeilenweise im Format\n"
+ "<host> <port> <IN|OUT>\n"
+ "an.",
MessageType.ERROR, null, null);
}
if (newdoc != null) {
tpNetworkRules.setDocument(newdoc);
}
if (invalid) {
return null;
}
// Success
return rulesList;
}
private int addLine(DefaultStyledDocument doc, String line, Color color, boolean bold) {
if (doc == null)
return 0;
if (color == null) {
color = FOREGROUND_TEXT_COLOR;
}
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setForeground(attrs, color);
StyleConstants.setBold(attrs, bold);
try {
doc.insertString(doc.getLength(), line + "\n", attrs);
} catch (BadLocationException e) {
LOGGER.warn("Cannot append to new textbox document", e);
}
return 1;
}
/**
* Very simple hostname check for the given String. This will only check for
* some requirements of valid hostnames as stated in
* http://tools.ietf.org/html/rfc1034#section-3.1 To recap: max length of
* the whole hostname must be < 254 ASCII characters, all domain labels
* (between two dots) must be between 1 and 63 chars long and domain labels
* can only contain digits, letters and hyphen. (Note: we also accept
* forward slash to accept subnets!)
*
* @param hostname the hostname to check for syntactical validity
* @return null if valid, error string otherwise
*/
private String checkHostnameSimple(final String hostname) {
if (hostname.length() > 254) {
return "Hostname ist zu lang.";
}
// split by '.' to get domain levels
boolean allNumeric = true;
String[] domainLabels = hostname.split("\\.");
for (String domainLabel : domainLabels) {
if (domainLabel.length() > 63) {
// fail since domain level should be max 63 chars
return "Domain-Ebene '" + domainLabel + "' länger als 63 Zeichen.";
}
if (Util.parseInt(domainLabel, -1) == -1) {
allNumeric = false;
}
// checking for valid chars is pointless with punycode
}
if (allNumeric && domainLabels.length != 4) {
return "Unvollständige IP-Adresse.";
}
return null;
}
}
/**
* Internal layout class for this widget
*/
class NetrulesConfiguratorLayout extends JPanel {
private static final long serialVersionUID = 5266120380443817325L;
private final static String txtNetworkOptionsTitle = "Netzwerk Einstellungen";
private final static String txtNetworkOptionsDesc = "Wenn Sie den Internetzugriff deaktiviert haben,"
+ " können Sie hier Ausnahmen definieren (Whitelist)."
+ " Bitte definieren Sie Ihre Regeln im Format\n<host> <port> <in|out>.\n"
+ "Sie können Port 0 angeben, was sämtlichen TCP und UDP Ports eines Hosts entspricht.\n\n"
+ "Wenn Sie Internetzugriff aktivieren, hat diese Liste den gegenteiligen Effekt";
private final static String txtNetworkRulesTitle = "Netzwerkregeln";
private final JPanel pnlNetworkOptions;
protected final JTextPane tpNetworkRules;
public NetrulesConfiguratorLayout() {
GridManager grid = new GridManager(this, 1, true,
new Insets(5, 5, 5, 5));
// middle panel for network rules
pnlNetworkOptions = new JPanel();
GridManager gridNetworkOptions = new GridManager(pnlNetworkOptions, 1,
true, new Insets(2, 2, 2, 2));
pnlNetworkOptions.setBorder(BorderFactory
.createTitledBorder(txtNetworkOptionsTitle));
tpNetworkRules = new JTextPane();
JScrollPane scpNetworkRules = new JScrollPane(tpNetworkRules,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
pnlNetworkOptions.setBorder(BorderFactory
.createTitledBorder(txtNetworkRulesTitle));
gridNetworkOptions
.add(new WordWrapLabel(txtNetworkOptionsDesc))
.fill(true, false).expand(true, false);
gridNetworkOptions.nextRow();
gridNetworkOptions.add(scpNetworkRules).fill(true, true)
.expand(true, true);
gridNetworkOptions.finish(false);
// build the final grid
grid.add(pnlNetworkOptions).fill(true, true).expand(true, true);
grid.finish(false);
}
}