use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class WebPlugin method setupServer.
protected void setupServer() {
try {
if (!plugin_enabled) {
if (tracker_context != null) {
tracker_context.destroy();
tracker_context = null;
}
return;
}
final int port = param_port.getValue();
String protocol_str = param_protocol.getValue().trim();
String bind_str = param_bind.getValue().trim();
InetAddress bind_ip = null;
if (bind_str.length() > 0) {
try {
bind_ip = InetAddress.getByName(bind_str);
} catch (Throwable e) {
}
if (bind_ip == null) {
// might be an interface name, see if we can resolve it
final NetworkAdmin na = NetworkAdmin.getSingleton();
InetAddress[] addresses = na.resolveBindAddresses(bind_str);
if (addresses.length > 0) {
bind_ip = addresses[0];
if (!na_intf_listener_added) {
na_intf_listener_added = true;
na.addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
@Override
public void propertyChanged(String property) {
if (unloaded) {
na.removePropertyChangeListener(this);
} else {
if (property == NetworkAdmin.PR_NETWORK_INTERFACES) {
new AEThread2("setupserver") {
@Override
public void run() {
setupServer();
}
}.start();
}
}
}
});
}
}
}
if (bind_ip == null) {
log.log(LoggerChannel.LT_ERROR, "Bind IP parameter '" + bind_str + "' is invalid");
}
}
if (tracker_context != null) {
URL url = tracker_context.getURLs()[0];
String existing_protocol = url.getProtocol();
int existing_port = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
InetAddress existing_bind_ip = tracker_context.getBindIP();
if (existing_port == port && existing_protocol.equalsIgnoreCase(protocol_str) && sameAddress(bind_ip, existing_bind_ip)) {
return;
}
tracker_context.destroy();
tracker_context = null;
}
int protocol = protocol_str.equalsIgnoreCase("HTTP") ? Tracker.PR_HTTP : Tracker.PR_HTTPS;
Map<String, Object> tc_properties = new HashMap<>();
Boolean prop_non_blocking = (Boolean) properties.get(PR_NON_BLOCKING);
if (prop_non_blocking != null && prop_non_blocking) {
tc_properties.put(Tracker.PR_NON_BLOCKING, true);
}
log.log(LoggerChannel.LT_INFORMATION, "Server initialisation: port=" + port + (bind_ip == null ? "" : (", bind=" + bind_str + "->" + bind_ip + ")")) + ", protocol=" + protocol_str + (root_dir.length() == 0 ? "" : (", root=" + root_dir)) + (properties.size() == 0 ? "" : (", props=" + properties)));
tracker_context = plugin_interface.getTracker().createWebContext(Constants.APP_NAME + " - " + plugin_interface.getPluginName(), port, protocol, bind_ip, tc_properties);
Boolean prop_enable_i2p = (Boolean) properties.get(PR_ENABLE_I2P);
if (prop_enable_i2p == null || prop_enable_i2p) {
network_dispatcher.dispatch(new AERunnable() {
@Override
public void runSupport() {
Map<String, Object> options = new HashMap<>();
options.put(AEProxyFactory.SP_PORT, port);
Map<String, Object> reply = AEProxyFactory.getPluginServerProxy(plugin_interface.getPluginName(), AENetworkClassifier.AT_I2P, plugin_interface.getPluginID(), options);
if (reply != null) {
param_i2p_dest.setVisible(true);
String host = (String) reply.get("host");
if (!param_i2p_dest.getValue().equals(host)) {
param_i2p_dest.setValue(host);
if (p_sid != null) {
updatePairing(p_sid);
}
}
}
}
});
}
Boolean prop_enable_tor = (Boolean) properties.get(PR_ENABLE_TOR);
if (prop_enable_tor == null || prop_enable_tor) {
network_dispatcher.dispatch(new AERunnable() {
@Override
public void runSupport() {
Map<String, Object> options = new HashMap<>();
options.put(AEProxyFactory.SP_PORT, port);
Map<String, Object> reply = AEProxyFactory.getPluginServerProxy(plugin_interface.getPluginName(), AENetworkClassifier.AT_TOR, plugin_interface.getPluginID(), options);
if (reply != null) {
param_tor_dest.setVisible(true);
String host = (String) reply.get("host");
if (!param_tor_dest.getValue().equals(host)) {
param_tor_dest.setValue(host);
if (p_sid != null) {
updatePairing(p_sid);
}
}
}
}
});
}
Boolean pr_enable_keep_alive = (Boolean) properties.get(PR_ENABLE_KEEP_ALIVE);
if (pr_enable_keep_alive != null && pr_enable_keep_alive) {
tracker_context.setEnableKeepAlive(true);
}
tracker_context.addPageGenerator(this);
tracker_context.addAuthenticationListener(new TrackerAuthenticationAdapter() {
private String last_pw = "";
private byte[] last_hash = {};
private final int DELAY = 10 * 1000;
private Map<String, Object[]> fail_map = new HashMap<>();
@Override
public boolean authenticate(String headers, URL resource, String user, String pw) {
// System.out.println( resource + ": " + user + "/" + pw );
long now = SystemTime.getMonotonousTime();
String client_address = getHeaderField(headers, "X-Real-IP");
if (client_address == null) {
client_address = "<unknown>";
}
synchronized (logout_timer) {
Long logout_time = logout_timer.get(client_address);
if (logout_time != null && now - logout_time <= LOGOUT_GRACE_MILLIS) {
tls.set(GRACE_PERIOD_MARKER);
return (true);
}
}
boolean result = authenticateSupport(headers, resource, user, pw);
if (!result) {
if (!pw.equals("")) {
AESemaphore waiter = null;
synchronized (fail_map) {
Object[] x = fail_map.get(client_address);
if (x == null) {
x = new Object[] { new AESemaphore("af:waiter"), new Long(-1), new Long(-1), now };
fail_map.put(client_address, x);
} else {
x[1] = x[2];
x[2] = x[3];
x[3] = now;
long t = (Long) x[1];
if (now - t < 10 * 1000) {
log("Too many recent authentication failures from '" + client_address + "' - rate limiting");
x[2] = now + DELAY;
// there's a bug where flipping the password on doesn't reset the pw so we automatically fail without checking
// this is not the correct fix, but it works
last_pw = "";
waiter = (AESemaphore) x[0];
}
}
}
if (waiter != null) {
waiter.reserve(DELAY);
}
}
} else {
synchronized (fail_map) {
fail_map.remove(client_address);
}
String cookies = getHeaderField(headers, "Cookie");
if (pairing_session_code != null) {
if (cookies == null || !cookies.contains(pairing_session_code)) {
tls.set(pairing_session_code);
}
}
}
recordAuthRequest(client_address, result);
if (!result) {
// going to be generous here as (old android browsers at least) sometimes fail to provide
// auth on .png files
// no I'm not, too many risks associated with this (e.g. xmwebui has some
// prefix url logic which may be exploitable)
// if ( resource.getPath().endsWith( ".png" )){
//
// result = true;
// }
}
return (result);
}
private boolean authenticateSupport(String headers, URL resource, String user, String pw) {
boolean result;
boolean auto_auth = param_auto_auth != null && param_auto_auth.getValue();
if (!pw_enable.getValue()) {
String whitelist = p_no_pw_whitelist.getValue().trim();
if (whitelist.equals("*")) {
result = true;
} else {
String actual_host = getHeaderField(headers, "host");
int actual_port = protocol == Tracker.PR_HTTP ? 80 : 443;
String referrer = getHeaderField(headers, "referer");
if (actual_host.startsWith("[")) {
int pos = actual_host.lastIndexOf(']');
if (pos != -1) {
String rem = actual_host.substring(pos + 1);
actual_host = actual_host.substring(0, pos + 1);
pos = rem.indexOf(':');
if (pos != -1) {
actual_port = Integer.parseInt(rem.substring(pos + 1).trim());
}
}
} else {
int pos = actual_host.indexOf(':');
if (pos != -1) {
actual_port = Integer.parseInt(actual_host.substring(pos + 1).trim());
actual_host = actual_host.substring(0, pos);
}
}
String[] allowed = whitelist.split(",");
result = false;
String msg = "";
if (actual_port != port) {
msg = "port mismatch: " + port + "/" + actual_port;
} else {
for (String a : allowed) {
a = a.trim();
if (a.equals("$")) {
InetAddress bind = getServerBindIP();
if (bind != null) {
if (bind instanceof Inet6Address) {
a = "[" + bind.getHostAddress() + "]";
} else {
a = bind.getHostAddress();
}
}
}
if (actual_host.equals(a.trim())) {
result = true;
break;
}
// Support ranges (copied from code in setupAccess)
IPRange ip_range = plugin_interface.getIPFilter().createRange(true);
String aTrimmed = a.trim();
int sep = aTrimmed.indexOf("-");
if (sep == -1) {
ip_range.setStartIP(aTrimmed);
ip_range.setEndIP(aTrimmed);
} else {
ip_range.setStartIP(aTrimmed.substring(0, sep).trim());
ip_range.setEndIP(aTrimmed.substring(sep + 1).trim());
}
ip_range.checkValid();
if (ip_range.isValid() && ip_range.isInRange(actual_host)) {
result = true;
break;
}
}
if (!result) {
msg = "host '" + actual_host + "' not in whitelist";
} else {
if (referrer != null) {
result = false;
try {
URL url = new URL(referrer);
int ref_port = url.getPort();
if (ref_port == -1) {
ref_port = url.getDefaultPort();
}
if (ref_port == port) {
result = true;
}
} catch (Throwable e) {
}
if (!result) {
msg = "referrer mismatch: " + referrer;
}
}
}
}
if (!result) {
log.log("Access denied: No password and " + msg);
}
}
} else {
if (auto_auth) {
user = user.trim().toLowerCase();
pw = pw.toUpperCase();
}
if (!user.equals(p_user_name.getValue())) {
log.log("Access denied: Incorrect user name: " + user);
result = false;
} else {
byte[] hash = last_hash;
if (!last_pw.equals(pw)) {
hash = plugin_interface.getUtilities().getSecurityManager().calculateSHA1(auto_auth ? pw.toUpperCase().getBytes() : pw.getBytes());
last_pw = pw;
last_hash = hash;
}
result = Arrays.equals(hash, p_password.getValue());
if (!result) {
log.log("Access denied: Incorrect password");
}
}
}
if (result) {
// user name and password match, see if we've come from the pairing process
checkCookieSet(headers, resource);
} else if (auto_auth) {
// either the ac is in the url, referer or we have a cookie set
int x = checkCookieSet(headers, resource);
if (x == 1) {
result = true;
} else if (x == 0) {
result = hasOurCookie(getHeaderField(headers, "Cookie"));
}
} else {
result = hasOurCookie(getHeaderField(headers, "Cookie"));
}
return (result);
}
/**
* @param headers
* @param resource
* @return 0 = unknown, 1 = ok, 2 = bad
*/
private int checkCookieSet(String headers, URL resource) {
if (pairing_access_code == null) {
return (2);
}
String[] locations = { resource.getQuery(), getHeaderField(headers, "Referer") };
for (String location : locations) {
if (location != null) {
boolean skip_fail = false;
int param_len = 0;
int p1 = location.indexOf("vuze_pairing_ac=");
if (p1 == -1) {
p1 = location.indexOf("ac=");
if (p1 != -1) {
param_len = 3;
skip_fail = true;
}
} else {
param_len = 16;
}
if (p1 != -1) {
int p2 = location.indexOf('&', p1);
String ac = location.substring(p1 + param_len, p2 == -1 ? location.length() : p2).trim();
p2 = ac.indexOf('#');
if (p2 != -1) {
ac = ac.substring(0, p2);
}
if (ac.equalsIgnoreCase(pairing_access_code)) {
tls.set(pairing_session_code);
return (1);
} else {
if (!skip_fail) {
return (2);
}
}
}
}
}
return (0);
}
private String getHeaderField(String headers, String field) {
String[] lines = headers.split("\n");
for (String line : lines) {
int pos = line.indexOf(':');
if (pos != -1) {
if (line.substring(0, pos).equalsIgnoreCase(field)) {
return (line.substring(pos + 1).trim());
}
}
}
return (null);
}
});
} catch (TrackerException e) {
log.log("Server initialisation failed", e);
}
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class PMSWTImpl method initialise.
@Override
public void initialise(final PluginInterface pi, final BooleanParameter icon_enable) {
final NetworkAdmin na = NetworkAdmin.getSingleton();
na.addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
@Override
public void propertyChanged(String property) {
if (property == NetworkAdmin.PR_NETWORK_INTERFACES) {
updateLocalAddresses(na);
}
}
});
updateLocalAddresses(na);
pi.getUIManager().addUIListener(new UIManagerListener() {
@Override
public void UIAttached(final UIInstance instance) {
if (instance instanceof UISWTInstance) {
UIFunctions uif = UIFunctionsManager.getUIFunctions();
if (uif != null) {
uiUpdaterListener = new UIUpdaterListener() {
@Override
public void updateComplete(int count) {
last_update_count = count;
updateStatus(true);
}
};
uif.getUIUpdater().addListener(uiUpdaterListener);
}
Utils.execSWTThread(new AERunnable() {
@Override
public void runSupport() {
ImageLoader imageLoader = ImageLoader.getInstance();
icon_idle = imageLoader.getImage("pair_sb_idle");
icon_green = imageLoader.getImage("pair_sb_green");
icon_red = imageLoader.getImage("pair_sb_red");
UISWTInstance ui_instance = (UISWTInstance) instance;
status = ui_instance.createStatusEntry();
last_tooltip_text = MessageText.getString("pairing.ui.icon.tip");
status.setTooltipText(last_tooltip_text);
status.setImageEnabled(true);
status.setImage(icon_idle);
last_image = icon_idle;
boolean is_visible = icon_enable.getValue();
status.setVisible(is_visible);
if (is_visible) {
updateStatus(false);
}
final MenuItem mi_show = pi.getUIManager().getMenuManager().addMenuItem(status.getMenuContext(), "pairing.ui.icon.show");
mi_show.setStyle(MenuItem.STYLE_CHECK);
mi_show.setData(Boolean.valueOf(is_visible));
mi_show.addListener(new MenuItemListener() {
@Override
public void selected(MenuItem menu, Object target) {
icon_enable.setValue(false);
}
});
iconEnableListener = new ParameterListener() {
@Override
public void parameterChanged(Parameter param) {
boolean is_visible = icon_enable.getValue();
status.setVisible(is_visible);
mi_show.setData(Boolean.valueOf(is_visible));
if (is_visible) {
updateStatus(false);
}
}
};
icon_enable.addListener(iconEnableListener);
MenuItem mi_pairing = pi.getUIManager().getMenuManager().addMenuItem(status.getMenuContext(), "MainWindow.menu.pairing");
mi_pairing.addListener(new MenuItemListener() {
@Override
public void selected(MenuItem menu, Object target) {
UIFunctions uif = UIFunctionsManager.getUIFunctions();
if (uif == null) {
Debug.out("UIFunctions not available, can't open remote pairing window");
} else {
uif.openRemotePairingWindow();
}
}
});
MenuItem mi_sep = pi.getUIManager().getMenuManager().addMenuItem(status.getMenuContext(), "");
mi_sep.setStyle(MenuItem.STYLE_SEPARATOR);
MenuItem mi_options = pi.getUIManager().getMenuManager().addMenuItem(status.getMenuContext(), "MainWindow.menu.view.configuration");
mi_options.addListener(new MenuItemListener() {
@Override
public void selected(MenuItem menu, Object target) {
UIFunctions uif = UIFunctionsManager.getUIFunctions();
if (uif != null) {
uif.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, PairingManager.CONFIG_SECTION_ID);
}
}
});
UISWTStatusEntryListener click_listener = new UISWTStatusEntryListener() {
@Override
public void entryClicked(UISWTStatusEntry entry) {
UIFunctions uif = UIFunctionsManager.getUIFunctions();
if (uif != null) {
uif.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, PairingManager.CONFIG_SECTION_ID);
}
}
};
status.setListener(click_listener);
}
});
}
}
@Override
public void UIDetached(UIInstance instance) {
if (instance instanceof UISWTInstance) {
UIFunctions uif = UIFunctionsManager.getUIFunctions();
if (uif != null && uiUpdaterListener != null) {
uif.getUIUpdater().removeListener(uiUpdaterListener);
uiUpdaterListener = null;
}
if (status != null) {
// menu items get destroyed with this call
status.destroy();
status = null;
}
if (icon_enable != null && iconEnableListener != null) {
icon_enable.removeListener(iconEnableListener);
iconEnableListener = null;
}
}
}
});
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class ConfigSectionLogging method configSectionCreate.
@Override
public Composite configSectionCreate(final Composite parent) {
ImageLoader imageLoader = ImageLoader.getInstance();
Image imgOpenFolder = imageLoader.getImage("openFolderButton");
GridData gridData;
GridLayout layout;
Composite gLogging = new Composite(parent, SWT.NULL);
gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
Utils.setLayoutData(gLogging, gridData);
layout = new GridLayout();
layout.numColumns = 2;
gLogging.setLayout(layout);
int userMode = COConfigurationManager.getIntParameter("User Mode");
BooleanParameter enable_logger = new BooleanParameter(gLogging, "Logger.Enabled", "ConfigView.section.logging.loggerenable");
gridData = new GridData();
gridData.horizontalSpan = 2;
enable_logger.setLayoutData(gridData);
// row
final BooleanParameter enableLogging = new BooleanParameter(gLogging, "Logging Enable", "ConfigView.section.logging.enable");
gridData = new GridData();
gridData.horizontalSpan = 2;
enableLogging.setLayoutData(gridData);
Composite cArea = new Composite(gLogging, SWT.NULL);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.numColumns = 3;
cArea.setLayout(layout);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
cArea.setLayoutData(gridData);
// row
Label lStatsPath = new Label(cArea, SWT.NULL);
// $NON-NLS-1$
Messages.setLanguageText(lStatsPath, "ConfigView.section.logging.logdir");
gridData = new GridData();
gridData.widthHint = 150;
// $NON-NLS-1$ //$NON-NLS-2$
final StringParameter pathParameter = new StringParameter(cArea, "Logging Dir");
pathParameter.setLayoutData(gridData);
Button browse = new Button(cArea, SWT.PUSH);
browse.setImage(imgOpenFolder);
imgOpenFolder.setBackground(browse.getBackground());
browse.setToolTipText(MessageText.getString("ConfigView.button.browse"));
browse.addListener(SWT.Selection, new Listener() {
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
@Override
public void handleEvent(Event event) {
DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);
dialog.setFilterPath(pathParameter.getValue());
// $NON-NLS-1$
dialog.setText(MessageText.getString("ConfigView.section.logging.choosedefaultsavepath"));
String path = dialog.open();
if (path != null) {
pathParameter.setValue(path);
}
}
});
Label lMaxLog = new Label(cArea, SWT.NULL);
Messages.setLanguageText(lMaxLog, "ConfigView.section.logging.maxsize");
final String[] lmLabels = new String[logFileSizes.length];
final int[] lmValues = new int[logFileSizes.length];
for (int i = 0; i < logFileSizes.length; i++) {
int num = logFileSizes[i];
lmLabels[i] = " " + num + " MB";
lmValues[i] = num;
}
IntListParameter paramMaxSize = new IntListParameter(cArea, "Logging Max Size", lmLabels, lmValues);
gridData = new GridData();
gridData.horizontalSpan = 2;
paramMaxSize.setLayoutData(gridData);
if (userMode > 1) {
Label timeStampLbl = new Label(cArea, SWT.NULL);
Messages.setLanguageText(timeStampLbl, "ConfigView.section.logging.timestamp");
Utils.setLayoutData(timeStampLbl, new GridData());
StringParameter timeStamp = new StringParameter(cArea, "Logging Timestamp");
gridData = new GridData();
gridData.horizontalSpan = 2;
gridData.widthHint = 150;
timeStamp.setLayoutData(gridData);
}
/**
* FileLogging filter, consisting of a List of types (info, warning, error)
* and a checkbox Table of component IDs.
*/
final String sFilterPrefix = "ConfigView.section.logging.filter";
Group gLogIDs = new Group(gLogging, SWT.NULL);
Messages.setLanguageText(gLogIDs, sFilterPrefix);
layout = new GridLayout();
layout.numColumns = 2;
gLogIDs.setLayout(layout);
gridData = new GridData(SWT.BEGINNING, SWT.BEGINNING, true, true);
gridData.horizontalSpan = 2;
Utils.setLayoutData(gLogIDs, gridData);
final List listLogTypes = new List(gLogIDs, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
gridData = new GridData(SWT.NULL, SWT.BEGINNING, false, false);
listLogTypes.setLayoutData(gridData);
final int[] logTypes = { LogEvent.LT_INFORMATION, LogEvent.LT_WARNING, LogEvent.LT_ERROR };
for (int i = 0; i < logTypes.length; i++) listLogTypes.add(MessageText.getString("ConfigView.section.logging.log" + i + "type"));
listLogTypes.select(0);
final LogIDs[] logIDs = FileLogging.configurableLOGIDs;
// Arrays.sort(logIDs);
final Table tableLogIDs = new Table(gLogIDs, SWT.CHECK | SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
gridData = new GridData(GridData.FILL_BOTH);
tableLogIDs.setLayoutData(gridData);
tableLogIDs.setLinesVisible(false);
tableLogIDs.setHeaderVisible(false);
TableColumn column = new TableColumn(tableLogIDs, SWT.NONE);
for (int i = 0; i < logIDs.length; i++) {
TableItem item = new TableItem(tableLogIDs, SWT.NULL);
item.setText(0, MessageText.getString(sFilterPrefix + "." + logIDs[i], logIDs[i].toString()));
item.setData(logIDs[i]);
boolean checked = COConfigurationManager.getBooleanParameter("bLog." + logTypes[0] + "." + logIDs[i], true);
item.setChecked(checked);
}
column.pack();
// Update table when list selection changes
listLogTypes.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int index = listLogTypes.getSelectionIndex();
if (index < 0 || index >= logTypes.length)
return;
TableItem[] items = tableLogIDs.getItems();
for (int i = 0; i < items.length; i++) {
boolean checked = COConfigurationManager.getBooleanParameter("bLog." + logTypes[index] + "." + items[i].getData(), true);
items[i].setChecked(checked);
}
}
});
// Save config when checkbox is clicked
tableLogIDs.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (e.detail != SWT.CHECK)
return;
int index = listLogTypes.getSelectionIndex();
if (index < 0 || index >= logTypes.length)
return;
TableItem item = (TableItem) e.item;
COConfigurationManager.setParameter("bLog." + logTypes[index] + "." + item.getData(), item.getChecked());
}
});
final Control[] controls_main = { cArea, gLogIDs };
final ChangeSelectionActionPerformer perf2 = new ChangeSelectionActionPerformer(controls_main);
enableLogging.setAdditionalActionPerformer(perf2);
enable_logger.setAdditionalActionPerformer(new IAdditionalActionPerformer() {
ChangeSelectionActionPerformer p1 = new ChangeSelectionActionPerformer(new Control[] { enableLogging.getControl() });
@Override
public void performAction() {
p1.performAction();
}
@Override
public void setSelected(boolean selected) {
p1.setSelected(selected);
if (!selected && enableLogging.isSelected())
enableLogging.setSelected(false);
}
@Override
public void setIntValue(int value) {
/*nothing*/
}
@Override
public void setStringValue(String value) {
/*nothing*/
}
});
if (userMode > 0) {
Composite cDebugFiles = new Composite(gLogging, SWT.NULL);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.numColumns = 3;
cDebugFiles.setLayout(layout);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
cDebugFiles.setLayoutData(gridData);
Label l_debug_file_size = new Label(cDebugFiles, SWT.NULL);
Messages.setLanguageText(l_debug_file_size, "ConfigView.section.logging.debugfilesize");
l_debug_file_size.setLayoutData(new GridData());
new IntParameter(cDebugFiles, "Logger.DebugFiles.SizeKB", 10, Integer.MAX_VALUE);
new Label(cDebugFiles, SWT.NULL).setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
if (userMode > 1) {
// advanced option
Group cAO = new Group(gLogging, SWT.NULL);
cAO.setText(MessageText.getString("dht.advanced.group"));
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.numColumns = 5;
cAO.setLayout(layout);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
cAO.setLayoutData(gridData);
// name
Label aoName = new Label(cAO, SWT.NULL);
Messages.setLanguageText(aoName, "label.name");
aoName.setLayoutData(new GridData());
final StringParameter name = new StringParameter(cAO, "Advanced Option Name");
gridData = new GridData();
gridData.widthHint = 150;
name.setLayoutData(gridData);
// value
Label aoValue = new Label(cAO, SWT.NULL);
Messages.setLanguageText(aoValue, "label.value");
aoName.setLayoutData(new GridData());
final StringParameter value = new StringParameter(cAO, "Advanced Option Value");
gridData = new GridData();
gridData.widthHint = 150;
value.setLayoutData(gridData);
// set
Button set_option = new Button(cAO, SWT.PUSH);
Messages.setLanguageText(set_option, "Button.set");
set_option.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
String key = name.getValue().trim();
if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) {
key = key.substring(1, key.length() - 1);
}
if (key.length() > 0) {
if (key.startsWith("!")) {
key = key.substring(1);
} else {
key = "adv.setting." + key;
}
String val = value.getValue().trim();
boolean is_string = false;
if ((val.startsWith("'") && val.endsWith("'")) || (val.startsWith("\"") && val.endsWith("\""))) {
val = val.substring(1, val.length() - 1);
is_string = true;
}
if (val.length() == 0) {
COConfigurationManager.removeParameter(key);
} else {
if (is_string) {
COConfigurationManager.setParameter(key, val);
} else {
String lc_val = val.toLowerCase(Locale.US);
if (lc_val.equals("false") || lc_val.equals("true")) {
COConfigurationManager.setParameter(key, lc_val.startsWith("t"));
} else {
try {
long l = Long.parseLong(val);
COConfigurationManager.setParameter(key, l);
} catch (Throwable e) {
COConfigurationManager.setParameter(key, val);
}
}
}
}
COConfigurationManager.save();
}
}
});
}
// network diagnostics
Label generate_net_info = new Label(gLogging, SWT.NULL);
Messages.setLanguageText(generate_net_info, "ConfigView.section.logging.netinfo");
Button generate_net_button = new Button(gLogging, SWT.PUSH);
Messages.setLanguageText(generate_net_button, "ConfigView.section.logging.generatediagnostics");
generate_net_button.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
new AEThread2("GenerateNetDiag", true) {
@Override
public void run() {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
IndentWriter iw = new IndentWriter(pw);
NetworkAdmin admin = NetworkAdmin.getSingleton();
admin.generateDiagnostics(iw);
pw.close();
final String info = sw.toString();
Logger.log(new LogEvent(LOGID, "Network Info:\n" + info));
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
ClipboardCopy.copyToClipBoard(info);
}
});
}
}.start();
}
});
// stats
Label generate_stats_info = new Label(gLogging, SWT.NULL);
Messages.setLanguageText(generate_stats_info, "ConfigView.section.logging.statsinfo");
Button generate_stats_button = new Button(gLogging, SWT.PUSH);
Messages.setLanguageText(generate_stats_button, "ConfigView.section.logging.generatediagnostics");
generate_stats_button.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
java.util.Set types = new HashSet();
types.add(CoreStats.ST_ALL);
Map reply = CoreStats.getStats(types);
Iterator it = reply.entrySet().iterator();
StringBuilder buffer = new StringBuilder(16000);
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
buffer.append(entry.getKey()).append(" -> ").append(entry.getValue()).append("\r\n");
}
String str = buffer.toString();
ClipboardCopy.copyToClipBoard(str);
Logger.log(new LogEvent(LOGID, "Stats Info:\n" + str));
}
});
// diagnostics
Label generate_info = new Label(gLogging, SWT.NULL);
Messages.setLanguageText(generate_info, "ConfigView.section.logging.generatediagnostics.info");
Button generate_button = new Button(gLogging, SWT.PUSH);
Messages.setLanguageText(generate_button, "ConfigView.section.logging.generatediagnostics");
generate_button.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
AEDiagnostics.generateEvidence(pw);
pw.close();
String evidence = sw.toString();
ClipboardCopy.copyToClipBoard(evidence);
Logger.log(new LogEvent(LOGID, "Evidence Generation:\n" + evidence));
}
});
if (false) {
Button test_button = new Button(gLogging, SWT.PUSH);
test_button.setText("Test");
test_button.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
try {
PluginInterface pi = CoreFactory.getSingleton().getPluginManager().getDefaultPluginInterface();
UpdateInstaller installer = pi.getUpdateManager().createInstaller();
installer.addMoveAction("C:\\temp\\file1", "C:\\temp\\file2");
installer.installNow(new UpdateInstallerListener() {
@Override
public void reportProgress(String str) {
System.out.println(str);
}
@Override
public void complete() {
System.out.println("complete");
}
@Override
public void failed(UpdateException e) {
System.out.println("failed");
e.printStackTrace();
}
});
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
return gLogging;
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class ClientIDManagerImpl method setGenerator.
public void setGenerator(ClientIDGenerator _generator, boolean _use_filter) {
generator = _generator;
use_filter = _use_filter;
if (!use_filter) {
// another reason for NOT doing this is if the user has a defined proxy
// in this case the assumption is that they know what they're doing and
// the proxy will be bound correctly to ensure that things work...
String http_proxy = System.getProperty("http.proxyHost");
String socks_proxy = System.getProperty("socksProxyHost");
NetworkAdmin network_admin = NetworkAdmin.getSingleton();
if (network_admin.mustBind()) {
filter_override = true;
use_filter = true;
} else {
InetAddress bindIP = network_admin.getSingleHomedServiceBindAddress();
if ((http_proxy == null || http_proxy.trim().length() == 0) && (socks_proxy == null || socks_proxy.trim().length() == 0) && (bindIP != null && !bindIP.isAnyLocalAddress())) {
int ips = 0;
try {
List<NetworkInterface> x = NetUtils.getNetworkInterfaces();
for (NetworkInterface network_interface : x) {
Enumeration<InetAddress> addresses = network_interface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress()) {
ips++;
}
}
}
} catch (Throwable e) {
Logger.log(new LogEvent(LOGID, "", e));
}
if (ips > 1) {
filter_override = true;
use_filter = true;
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "ClientIDManager: overriding filter " + "option to support local bind IP"));
}
}
}
}
setupFilter(false);
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class TransferStatsView method refreshConnectionPanel.
private void refreshConnectionPanel() {
if (global_manager == null) {
return;
}
int total_connections = 0;
int total_con_queued = 0;
int total_con_blocked = 0;
int total_con_unchoked = 0;
int total_data_queued = 0;
int total_in = 0;
List<DownloadManager> dms = global_manager.getDownloadManagers();
for (DownloadManager dm : dms) {
PEPeerManager pm = dm.getPeerManager();
if (pm != null) {
total_data_queued += pm.getBytesQueuedForUpload();
total_connections += pm.getNbPeers() + pm.getNbSeeds();
total_con_queued += pm.getNbPeersWithUploadQueued();
total_con_blocked += pm.getNbPeersWithUploadBlocked();
total_con_unchoked += pm.getNbPeersUnchoked();
total_in += pm.getNbRemoteTCPConnections() + pm.getNbRemoteUDPConnections() + pm.getNbRemoteUTPConnections();
}
}
connection_label.setText(MessageText.getString("SpeedView.stats.con_details", new String[] { String.valueOf(total_connections) + "[" + MessageText.getString("label.in").toLowerCase() + ":" + total_in + "]", String.valueOf(total_con_unchoked), String.valueOf(total_con_queued), String.valueOf(total_con_blocked) }));
connection_graphic.addIntsValue(new int[] { total_connections, total_con_unchoked, total_con_queued, total_con_blocked });
upload_label.setText(MessageText.getString("SpeedView.stats.upload_details", new String[] { DisplayFormatters.formatByteCountToKiBEtc(total_data_queued) }));
upload_graphic.addIntValue(total_data_queued);
upload_graphic.refresh(false);
connection_graphic.refresh(false);
if (con_folder.getSelectionIndex() == 1) {
long now = SystemTime.getMonotonousTime();
if (now - last_route_update >= 2 * 1000) {
last_route_update = now;
NetworkAdmin na = NetworkAdmin.getSingleton();
Map<InetAddress, String> ip_to_name_map = new HashMap<>();
Map<String, RouteInfo> name_to_route_map = new HashMap<>();
RouteInfo udp_info = null;
RouteInfo unknown_info = null;
List<PRUDPPacketHandler> udp_handlers = PRUDPPacketHandlerFactory.getHandlers();
InetAddress udp_bind_ip = null;
for (PRUDPPacketHandler handler : udp_handlers) {
if (handler.hasPrimordialHandler()) {
udp_bind_ip = handler.getBindIP();
if (udp_bind_ip != null) {
if (udp_bind_ip.isAnyLocalAddress()) {
udp_bind_ip = null;
}
}
}
}
for (DownloadManager dm : dms) {
PEPeerManager pm = dm.getPeerManager();
if (pm != null) {
List<PEPeer> peers = pm.getPeers();
for (PEPeer p : peers) {
NetworkConnection nc = PluginCoreUtils.unwrap(p.getPluginConnection());
boolean done = false;
if (nc != null) {
Transport transport = nc.getTransport();
if (transport != null) {
InetSocketAddress notional_address = nc.getEndpoint().getNotionalAddress();
String ip = AddressUtils.getHostAddress(notional_address);
String network = AENetworkClassifier.categoriseAddress(ip);
if (network == AENetworkClassifier.AT_PUBLIC) {
if (transport.isTCP()) {
TransportStartpoint start = transport.getTransportStartpoint();
if (start != null) {
InetSocketAddress socket_address = start.getProtocolStartpoint().getAddress();
if (socket_address != null) {
InetAddress address = socket_address.getAddress();
String name;
if (address.isAnyLocalAddress()) {
name = "* (TCP)";
} else {
name = ip_to_name_map.get(address);
}
if (name == null) {
name = na.classifyRoute(address);
ip_to_name_map.put(address, name);
}
if (transport.isSOCKS()) {
name += " (SOCKS)";
}
RouteInfo info = name_to_route_map.get(name);
if (info == null) {
info = new RouteInfo(name);
name_to_route_map.put(name, info);
route_last_seen.put(name, now);
}
info.update(p);
done = true;
}
}
} else {
if (udp_bind_ip != null) {
RouteInfo info;
String name = ip_to_name_map.get(udp_bind_ip);
if (name == null) {
name = na.classifyRoute(udp_bind_ip);
ip_to_name_map.put(udp_bind_ip, name);
info = name_to_route_map.get(name);
route_last_seen.put(name, now);
if (info == null) {
info = new RouteInfo(name);
name_to_route_map.put(name, info);
}
} else {
info = name_to_route_map.get(name);
}
info.update(p);
done = true;
} else {
if (udp_info == null) {
udp_info = new RouteInfo("* (UDP)");
name_to_route_map.put(udp_info.getName(), udp_info);
route_last_seen.put(udp_info.getName(), now);
}
udp_info.update(p);
done = true;
}
}
} else {
RouteInfo info = name_to_route_map.get(network);
if (info == null) {
info = new RouteInfo(network);
name_to_route_map.put(network, info);
route_last_seen.put(network, now);
}
info.update(p);
done = true;
}
}
}
if (!done) {
if (unknown_info == null) {
unknown_info = new RouteInfo("Pending");
name_to_route_map.put(unknown_info.getName(), unknown_info);
route_last_seen.put(unknown_info.getName(), now);
}
unknown_info.update(p);
}
}
}
}
List<RouteInfo> rows = new ArrayList<>();
Iterator<Map.Entry<String, Long>> it = route_last_seen.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Long> entry = it.next();
long when = entry.getValue();
if (now - when > 60 * 1000) {
it.remove();
} else if (when != now) {
rows.add(new RouteInfo(entry.getKey()));
}
}
rows.addAll(name_to_route_map.values());
Collections.sort(rows, new Comparator<RouteInfo>() {
@Override
public int compare(RouteInfo o1, RouteInfo o2) {
String n1 = o1.getName();
String n2 = o2.getName();
// wildcard and pending to the bottom
if (n1.startsWith("*") || n1.equals("Pending")) {
n1 = "zzzz" + n1;
}
if (n2.startsWith("*") || n2.equals("Pending")) {
n2 = "zzzz" + n2;
}
return (n1.compareTo(n2));
}
});
buildRouteComponent(rows.size());
for (int i = 0; i < rows.size(); i++) {
RouteInfo info = rows.get(i);
route_labels[i][0].setText(info.getName());
route_labels[i][1].setText(info.getIncomingString());
route_labels[i][2].setText(info.getOutgoingString());
}
buildRouteComponent(rows.size());
}
}
}
Aggregations