use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class VersionCheckClient method preProcessReply.
protected void preProcessReply(Map reply, final boolean v6) {
NetworkAdmin admin = NetworkAdmin.getSingleton();
try {
byte[] address = (byte[]) reply.get("source_ip_address");
if (address != null) {
InetAddress my_ip = InetAddress.getByName(new String(address));
NetworkAdminASN old_asn = admin.getCurrentASN();
NetworkAdminASN new_asn = admin.lookupCurrentASN(my_ip);
if (!new_asn.sameAs(old_asn)) {
if (!secondary_check_done) {
secondary_check_done = true;
new AEThread("Secondary version check", true) {
@Override
public void runSupport() {
getVersionCheckInfoSupport(REASON_SECONDARY_CHECK, false, true, v6);
}
}.start();
}
}
}
} catch (Throwable e) {
if (!Debug.containsException(e, UnknownHostException.class)) {
Debug.printStackTrace(e);
}
}
Long as_advice = (Long) reply.get("as_advice");
if (as_advice != null) {
NetworkAdminASN current_asn = admin.getCurrentASN();
String asn = current_asn.getASName();
if (asn != null) {
long advice = as_advice.longValue();
if (advice != 0) {
// require crypto
String done_asn = COConfigurationManager.getStringParameter("ASN Advice Followed", "");
if (!done_asn.equals(asn)) {
COConfigurationManager.setParameter("ASN Advice Followed", asn);
boolean change = advice == 1 || advice == 2;
boolean alert = advice == 1 || advice == 3;
if (!COConfigurationManager.getBooleanParameter("network.transport.encrypted.require")) {
if (change) {
COConfigurationManager.setParameter("network.transport.encrypted.require", true);
}
if (alert) {
String msg = MessageText.getString("crypto.alert.as.warning", new String[] { asn });
Logger.log(new LogAlert(false, LogAlert.AT_WARNING, msg));
}
}
}
}
}
}
// set ui.toolbar.uiswitcher based on instructions from tracker
// Really shouldn't be in VersionCheck client, but instead have some
// listener and have the code elsewhere. Simply calling
// getVersionCheckInfo from "code elsewhere" (to get the cached result)
// caused a deadlock at startup.
Long lEnabledUISwitcher = (Long) reply.get("ui.toolbar.uiswitcher");
if (lEnabledUISwitcher != null) {
COConfigurationManager.setBooleanDefault("ui.toolbar.uiswitcher", lEnabledUISwitcher.longValue() == 1);
}
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class PRUDPPacketHandlerImpl method calcBind.
protected void calcBind() {
if (explicit_bind_ip != null) {
if (altProtocolDelegate != null) {
altProtocolDelegate.destroy();
altProtocolDelegate = null;
}
target_bind_ip = explicit_bind_ip;
} else {
InetAddress altAddress = null;
NetworkAdmin adm = NetworkAdmin.getSingleton();
try {
if (default_bind_ip instanceof Inet6Address && !default_bind_ip.isAnyLocalAddress() && adm.hasIPV4Potential())
altAddress = adm.getSingleHomedServiceBindAddress(NetworkAdmin.IP_PROTOCOL_VERSION_REQUIRE_V4);
else if (default_bind_ip instanceof Inet4Address && adm.hasIPV6Potential())
altAddress = adm.getSingleHomedServiceBindAddress(NetworkAdmin.IP_PROTOCOL_VERSION_REQUIRE_V6);
} catch (UnsupportedAddressTypeException e) {
}
if (altProtocolDelegate != null && !altProtocolDelegate.explicit_bind_ip.equals(altAddress)) {
altProtocolDelegate.destroy();
altProtocolDelegate = null;
}
if (altAddress != null && altProtocolDelegate == null) {
altProtocolDelegate = new PRUDPPacketHandlerImpl(port, altAddress, packet_transformer);
altProtocolDelegate.stats = stats;
altProtocolDelegate.primordial_handlers = primordial_handlers;
altProtocolDelegate.request_handler = request_handler;
}
target_bind_ip = default_bind_ip;
}
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class PEPeerTransportProtocol method sendAZHandshake.
private void sendAZHandshake() {
final Message[] avail_msgs = MessageManager.getSingleton().getRegisteredMessages();
final String[] avail_ids = new String[avail_msgs.length];
final byte[] avail_vers = new byte[avail_msgs.length];
for (int i = 0; i < avail_msgs.length; i++) {
avail_ids[i] = avail_msgs[i].getID();
avail_vers[i] = avail_msgs[i].getVersion();
}
int local_tcp_port = TCPNetworkManager.getSingleton().getTCPListeningPortNumber();
int local_udp_port = UDPNetworkManager.getSingleton().getUDPListeningPortNumber();
int local_udp2_port = UDPNetworkManager.getSingleton().getUDPNonDataListeningPortNumber();
String tcpPortOverride = COConfigurationManager.getStringParameter("TCP.Listen.Port.Override");
try {
local_tcp_port = Integer.parseInt(tcpPortOverride);
} catch (NumberFormatException e) // ignore as invalid input
{
}
boolean require_crypto = NetworkManager.getCryptoRequired(manager.getAdapter().getCryptoLevel());
/*
* we always send the Az-handshake immediately after the BT-handshake, before decoding the
* other side's Az-handshake, thus there should be no peerSessionID unless this is a
* reconnect
*/
if (peerSessionID != null)
Logger.log(new LogEvent(this, LOGID, LogEvent.LT_INFORMATION, "notifying peer of reconnect attempt"));
InetAddress defaultV6 = null;
NetworkAdmin na = NetworkAdmin.getSingleton();
if (peer_item_identity.getNetwork() == AENetworkClassifier.AT_PUBLIC && !na.isSocksActive()) {
// don't send public address in handshake
defaultV6 = na.hasIPV6Potential(true) ? na.getDefaultPublicAddressV6() : null;
}
// String peer_name = Constants.BIGLY_PROTOCOL_NAME;
String client_name = (String) ClientIDManagerImpl.getSingleton().getProperty(manager.getHash(), ClientIDGenerator.PR_CLIENT_NAME);
int pos = client_name.indexOf(' ');
String peer_name;
String peer_version;
if (pos == -1) {
Debug.out("Unsupported client name: " + client_name);
peer_name = Constants.BIGLY_PROTOCOL_NAME;
peer_version = Constants.AZUREUS_VERSION;
} else {
peer_name = client_name.substring(0, pos);
pos = client_name.lastIndexOf(' ');
peer_version = client_name.substring(pos + 1);
}
AZHandshake az_handshake = new AZHandshake(AZPeerIdentityManager.getAZPeerIdentity(), mySessionID, peerSessionID, peer_name, peer_version, local_tcp_port, local_udp_port, local_udp2_port, defaultV6, manager.isPrivateTorrent() ? 0 : (is_metadata_download ? 0 : manager.getTorrentInfoDictSize()), avail_ids, avail_vers, require_crypto ? AZHandshake.HANDSHAKE_TYPE_CRYPTO : AZHandshake.HANDSHAKE_TYPE_PLAIN, other_peer_handshake_version, manager.isSeeding() && !(ENABLE_LAZY_BITFIELD || manual_lazy_bitfield_control));
connection.getOutgoingMessageQueue().addMessage(az_handshake, false);
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class CoreImpl method start.
@Override
public void start() throws CoreException {
if (!canStart()) {
throw (new CoreException("Core: already started (alternative process)"));
}
AEThread2.setOurThread();
try {
this_mon.enter();
if (started) {
throw (new CoreException("Core: already started"));
}
if (stopped) {
throw (new CoreException("Core: already stopped"));
}
started = true;
} finally {
this_mon.exit();
}
// If a user sets this property, it is an alias for the following settings.
if ("1".equals(System.getProperty(SystemProperties.SYSPROP_SAFEMODE))) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Safe mode enabled"));
Constants.isSafeMode = true;
System.setProperty(SystemProperties.SYSPROP_LOADPLUGINS, "0");
System.setProperty(SystemProperties.SYSPROP_DISABLEDOWNLOADS, "1");
System.setProperty(SystemProperties.SYSPROP_SKIP_SWTCHECK, "1");
// Not using localised text - not sure it's safe to this early.
Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogEvent.LT_WARNING, "You are running " + Constants.APP_NAME + " in safe mode - you " + "can change your configuration, but any downloads added will " + "not be remembered when you close " + Constants.APP_NAME + "."));
}
/**
* test to see if UI plays nicely with a really slow initialization
*/
String sDelayCore = System.getProperty("delay.core", null);
if (sDelayCore != null) {
try {
long delayCore = Long.parseLong(sDelayCore);
Thread.sleep(delayCore);
} catch (Exception e) {
e.printStackTrace();
}
}
// run plugin loading in parallel to the global manager loading
AEThread2 pluginload = new AEThread2("PluginLoader", true) {
@Override
public void run() {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Loading of Plugins starts"));
pi.loadPlugins(CoreImpl.this, false, !"0".equals(System.getProperty(SystemProperties.SYSPROP_LOADPLUGINS)), true, true);
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Loading of Plugins complete"));
}
};
if (LOAD_PLUGINS_IN_OTHER_THREAD) {
pluginload.start();
} else {
pluginload.run();
}
// Disable async loading of existing torrents, because there are many things
// (like hosting) that require all the torrents to be loaded. While we
// can write code for each of these cases to wait until the torrents are
// loaded, it's a pretty big job to find them all and fix all their quirks.
// Too big of a job for this late in the release stage.
// Other example is the tracker plugin that is coded in a way where it must
// always publish a complete rss feed
global_manager = GlobalManagerFactory.create(this, null, 0);
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
// wait until plugin loading is done
if (LOAD_PLUGINS_IN_OTHER_THREAD) {
pluginload.join();
}
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
VuzeFileHandler.getSingleton().addProcessor(new VuzeFileProcessor() {
@Override
public void process(VuzeFile[] files, int expected_types) {
for (int i = 0; i < files.length; i++) {
VuzeFile vf = files[i];
VuzeFileComponent[] comps = vf.getComponents();
for (int j = 0; j < comps.length; j++) {
VuzeFileComponent comp = comps[j];
int comp_type = comp.getType();
if (comp_type == VuzeFileComponent.COMP_TYPE_ADD_TORRENT) {
PluginInterface default_pi = getPluginManager().getDefaultPluginInterface();
Map map = comp.getContent();
try {
Torrent torrent;
String url = MapUtils.getMapString(map, "torrent_url", null);
if (url != null) {
TorrentDownloader dl = default_pi.getTorrentManager().getURLDownloader(new URL(url));
torrent = dl.download();
} else {
String tf = MapUtils.getMapString(map, "torrent_file", null);
if (tf != null) {
File file = new File(tf);
if (!file.canRead() || file.isDirectory()) {
throw (new Exception("torrent_file '" + tf + "' is invalid"));
}
torrent = default_pi.getTorrentManager().createFromBEncodedFile(file);
} else {
throw (new Exception("torrent_url or torrent_file must be specified"));
}
}
File dest = null;
String save_folder = MapUtils.getMapString(map, "save_folder", null);
if (save_folder != null) {
dest = new File(save_folder, torrent.getName());
} else {
String save_file = MapUtils.getMapString(map, "save_file", null);
if (save_file != null) {
dest = new File(save_file);
}
}
if (dest != null) {
dest.getParentFile().mkdirs();
}
default_pi.getDownloadManager().addDownload(torrent, null, dest);
} catch (Throwable e) {
Debug.out(e);
}
comp.setProcessed();
}
}
}
}
});
triggerLifeCycleComponentCreated(global_manager);
pi.initialisePlugins();
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Initializing Plugins complete"));
try {
PluginInterface dht_pi = getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);
if (dht_pi != null) {
dht_pi.addEventListener(new PluginEventListener() {
private boolean first_dht = true;
@Override
public void handleEvent(PluginEvent ev) {
if (ev.getType() == DHTPlugin.EVENT_DHT_AVAILABLE) {
if (first_dht) {
first_dht = false;
DHT dht = (DHT) ev.getValue();
dht.addListener(new DHTListener() {
@Override
public void speedTesterAvailable(DHTSpeedTester tester) {
if (speed_manager != null) {
speed_manager.setSpeedTester(tester);
}
}
});
global_manager.addListener(new GlobalManagerAdapter() {
@Override
public void seedingStatusChanged(boolean seeding_only_mode, boolean b) {
checkConfig();
}
});
COConfigurationManager.addAndFireParameterListeners(new String[] { TransferSpeedValidator.AUTO_UPLOAD_ENABLED_CONFIGKEY, TransferSpeedValidator.AUTO_UPLOAD_SEEDING_ENABLED_CONFIGKEY }, new ParameterListener() {
@Override
public void parameterChanged(String parameterName) {
checkConfig();
}
});
}
}
}
protected void checkConfig() {
if (speed_manager != null) {
speed_manager.setEnabled(TransferSpeedValidator.isAutoSpeedActive(global_manager));
}
}
});
}
} catch (Throwable e) {
}
if (COConfigurationManager.getBooleanParameter("Resume Downloads On Start")) {
global_manager.resumeDownloads();
}
VersionCheckClient.getSingleton().initialise();
instance_manager.initialize();
NetworkManager.getSingleton().initialize(this);
SpeedLimitHandler.getSingleton(this);
Runtime.getRuntime().addShutdownHook(new AEThread("Shutdown Hook") {
@Override
public void runSupport() {
Logger.log(new LogEvent(LOGID, "Shutdown hook triggered"));
CoreImpl.this.stop();
}
});
DelayedTask delayed_task = UtilitiesImpl.addDelayedTask("Core", new Runnable() {
@Override
public void run() {
new AEThread2("core:delayTask", true) {
@Override
public void run() {
AEDiagnostics.checkDumpsAndNatives();
COConfigurationManager.setParameter("diags.enable.pending.writes", true);
AEDiagnostics.flushPendingLogs();
NetworkAdmin na = NetworkAdmin.getSingleton();
na.runInitialChecks(CoreImpl.this);
na.addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
private String last_as;
@Override
public void propertyChanged(String property) {
NetworkAdmin na = NetworkAdmin.getSingleton();
if (property.equals(NetworkAdmin.PR_NETWORK_INTERFACES)) {
boolean found_usable = false;
NetworkAdminNetworkInterface[] intf = na.getInterfaces();
for (int i = 0; i < intf.length; i++) {
NetworkAdminNetworkInterfaceAddress[] addresses = intf[i].getAddresses();
for (int j = 0; j < addresses.length; j++) {
if (!addresses[j].isLoopback()) {
found_usable = true;
}
}
}
if (!found_usable) {
return;
}
Logger.log(new LogEvent(LOGID, "Network interfaces have changed (new=" + na.getNetworkInterfacesAsString() + ")"));
announceAll(false);
} else if (property.equals(NetworkAdmin.PR_AS)) {
String as = na.getCurrentASN().getAS();
if (last_as == null) {
last_as = as;
} else if (!as.equals(last_as)) {
Logger.log(new LogEvent(LOGID, "AS has changed (new=" + as + ")"));
last_as = as;
announceAll(false);
}
}
}
});
setupSleepAndCloseActions();
}
}.start();
}
});
delayed_task.queue();
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
PairingManagerFactory.getSingleton();
CoreRunningListener[] runningListeners;
mon_coreRunningListeners.enter();
try {
if (coreRunningListeners == null) {
runningListeners = new CoreRunningListener[0];
} else {
runningListeners = coreRunningListeners.toArray(new CoreRunningListener[0]);
coreRunningListeners = null;
}
} finally {
mon_coreRunningListeners.exit();
}
// Trigger Listeners now that core is started
new AEThread2("Plugin Init Complete", false) {
@Override
public void run() {
try {
PlatformManagerFactory.getPlatformManager().startup(CoreImpl.this);
} catch (Throwable e) {
Debug.out("PlatformManager: init failed", e);
}
Iterator it = lifecycle_listeners.iterator();
while (it.hasNext()) {
try {
CoreLifecycleListener listener = (CoreLifecycleListener) it.next();
if (!listener.requiresPluginInitCompleteBeforeStartedEvent()) {
listener.started(CoreImpl.this);
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
pi.initialisationComplete();
it = lifecycle_listeners.iterator();
while (it.hasNext()) {
try {
CoreLifecycleListener listener = (CoreLifecycleListener) it.next();
if (listener.requiresPluginInitCompleteBeforeStartedEvent()) {
listener.started(CoreImpl.this);
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
}.start();
// Typically there are many runningListeners, most with quick execution, and
// a few longer ones. Let 3 run at a time, queue the rest. Without
// a ThreadPool, the slow ones would delay the startup processes that run
// after this start() method
ThreadPool tp = new ThreadPool("Trigger CoreRunning Listeners", 3);
for (final CoreRunningListener l : runningListeners) {
try {
tp.run(new AERunnable() {
@Override
public void runSupport() {
l.coreRunning(CoreImpl.this);
}
});
} catch (Throwable t) {
Debug.out(t);
}
}
// Debug.out("Core Start Complete");
}
use of com.biglybt.core.networkmanager.admin.NetworkAdmin in project BiglyBT by BiglySoftware.
the class PEPeerTransportProtocol method sendLTHandshake.
private void sendLTHandshake() {
String client_name = (String) ClientIDManagerImpl.getSingleton().getProperty(manager.getHash(), ClientIDGenerator.PR_CLIENT_NAME);
int localTcpPort = TCPNetworkManager.getSingleton().getTCPListeningPortNumber();
String tcpPortOverride = COConfigurationManager.getStringParameter("TCP.Listen.Port.Override");
try {
localTcpPort = Integer.parseInt(tcpPortOverride);
}// ignore as invalid input
catch (NumberFormatException e) {
}
boolean require_crypto = NetworkManager.getCryptoRequired(manager.getAdapter().getCryptoLevel());
Map data_dict = new HashMap();
data_dict.put("v", client_name);
data_dict.put("p", new Integer(localTcpPort));
data_dict.put("e", new Long(require_crypto ? 1L : 0L));
boolean upload_only = manager.isSeeding() && !(ENABLE_LAZY_BITFIELD || manual_lazy_bitfield_control || manager.isSuperSeedMode());
// maintain this for any kinds of compatability
data_dict.put("upload_only", new Long(upload_only ? 1L : 0L));
int metainfo_size;
if (manager.isPrivateTorrent()) {
metainfo_size = 0;
} else {
metainfo_size = is_metadata_download ? 0 : manager.getTorrentInfoDictSize();
}
if (metainfo_size > 0) {
data_dict.put("metadata_size", new Integer(metainfo_size));
}
NetworkAdmin na = NetworkAdmin.getSingleton();
if (peer_item_identity.getNetwork() == AENetworkClassifier.AT_PUBLIC && !na.isSocksActive()) {
// don't send public address in handshake
InetAddress defaultV6 = na.hasIPV6Potential(true) ? na.getDefaultPublicAddressV6() : null;
if (defaultV6 != null) {
data_dict.put("ipv6", defaultV6.getAddress());
}
}
LTHandshake lt_handshake = new LTHandshake(data_dict, other_peer_bt_lt_ext_version);
lt_handshake.addDefaultExtensionMappings(true, is_metadata_download || metainfo_size > 0, true);
connection.getOutgoingMessageQueue().addMessage(lt_handshake, false);
}
Aggregations