use of com.biglybt.plugin.upnp.UPnPPlugin in project BiglyBT by BiglySoftware.
the class ClientMyInstanceImpl method readExternalAddress.
private InetAddress readExternalAddress() {
InetAddress external_address = null;
if (manager.isClosing()) {
external_address = last_external_address;
if (external_address == null) {
try {
external_address = InetAddress.getByName("127.0.0.1");
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
return (external_address);
}
DHTPlugin dht = adapter.getDHTPlugin();
if (dht_address != null && dht_address_time <= SystemTime.getCurrentTime()) {
ClientInstanceManagerAdapter.VCPublicAddress a = adapter.getVCPublicAddress();
if (a != null) {
long cache_time = a.getCacheTime();
if (cache_time <= dht_address_time) {
external_address = dht_address;
}
}
}
if (external_address == null && (dht == null || dht.getStatus() != DHTPlugin.STATUS_RUNNING)) {
// use cached version if available and the DHT isn't
ClientInstanceManagerAdapter.VCPublicAddress a = adapter.getVCPublicAddress();
if (a != null) {
try {
external_address = InetAddress.getByName(a.getAddress());
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
if (external_address == null && dht != null) {
try {
InetAddress latest_dht_address = dht.getLocalAddress().getAddress().getAddress();
if (sameFamily(internal_address, latest_dht_address)) {
external_address = latest_dht_address;
}
} catch (Throwable e) {
}
}
long now = SystemTime.getCurrentTime();
if (last_force_read_ext > now) {
last_force_read_ext = now;
}
boolean ok_to_try_ext = now - last_force_read_ext > FORCE_READ_EXT_MIN;
if (external_address == null && last_external_address != null) {
if (last_upnp_read > now) {
last_upnp_read = now;
}
if (now - last_upnp_read > UPNP_READ_MIN || ok_to_try_ext) {
last_upnp_read = now;
try {
UPnPPlugin upnp = adapter.getUPnPPlugin();
if (upnp != null) {
String[] addresses = upnp.getExternalIPAddresses();
for (int i = 0; i < addresses.length; i++) {
if (addresses[i].equals(last_external_address.getHostAddress())) {
external_address = last_external_address;
break;
}
}
}
} catch (Throwable e) {
}
}
}
if (external_address == null) {
if (ok_to_try_ext) {
last_force_read_ext = now;
external_address = adapter.getPublicAddress();
}
}
if (external_address == null) {
if (last_external_address != null) {
external_address = last_external_address;
} else {
try {
external_address = InetAddress.getByName("127.0.0.1");
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
} else {
last_external_address = external_address;
}
return (external_address);
}
use of com.biglybt.plugin.upnp.UPnPPlugin in project BiglyBT by BiglySoftware.
the class NetworkAdminImpl method getNATDevices.
@Override
public NetworkAdminNATDevice[] getNATDevices(Core core) {
List<NetworkAdminNATDeviceImpl> devices = new ArrayList<>();
try {
PluginInterface upnp_pi = core.getPluginManager().getPluginInterfaceByClass(UPnPPlugin.class);
if (upnp_pi != null) {
UPnPPlugin upnp = (UPnPPlugin) upnp_pi.getPlugin();
UPnPPluginService[] services = upnp.getServices();
for (UPnPPluginService service : services) {
NetworkAdminNATDeviceImpl dev = new NetworkAdminNATDeviceImpl(service);
boolean same = false;
for (NetworkAdminNATDeviceImpl d : devices) {
if (d.sameAs(dev)) {
same = true;
break;
}
}
if (!same) {
devices.add(dev);
}
}
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
return ((NetworkAdminNATDevice[]) devices.toArray(new NetworkAdminNATDevice[devices.size()]));
}
use of com.biglybt.plugin.upnp.UPnPPlugin in project BiglyBT by BiglySoftware.
the class NetworkAdminProtocolImpl method test.
@Override
public InetAddress test(NetworkAdminNetworkInterfaceAddress address, boolean upnp_map, NetworkAdminProgressListener listener) throws NetworkAdminException {
InetAddress bind_ip = address == null ? null : address.getAddress();
NetworkAdminProtocolTester tester;
if (type == PT_HTTP) {
tester = new NetworkAdminHTTPTester(core, listener);
} else if (type == PT_TCP) {
tester = new NetworkAdminTCPTester(core, listener);
} else {
tester = new NetworkAdminUDPTester(core, listener);
}
InetAddress res;
if (port <= 0) {
res = tester.testOutbound(bind_ip, 0);
} else {
UPnPMapping new_mapping = null;
if (upnp_map) {
PluginInterface pi_upnp = core.getPluginManager().getPluginInterfaceByClass(UPnPPlugin.class);
if (pi_upnp != null) {
UPnPPlugin upnp = (UPnPPlugin) pi_upnp.getPlugin();
UPnPMapping mapping = upnp.getMapping(type != PT_UDP, port);
if (mapping == null) {
new_mapping = mapping = upnp.addMapping("NAT Tester", type != PT_UDP, port, true);
try {
Thread.sleep(500);
} catch (Throwable e) {
}
}
}
}
try {
res = tester.testInbound(bind_ip, port);
} finally {
if (new_mapping != null) {
new_mapping.destroy();
}
}
}
return (res);
}
use of com.biglybt.plugin.upnp.UPnPPlugin in project BiglyBT by BiglySoftware.
the class DHTPlugin method initialize.
@Override
public void initialize(PluginInterface _plugin_interface) {
status = STATUS_INITALISING;
plugin_interface = _plugin_interface;
dht_data_port = UDPNetworkManager.getSingleton().getUDPNonDataListeningPortNumber();
log = plugin_interface.getLogger().getTimeStampedChannel(PLUGIN_NAME);
UIManager ui_manager = plugin_interface.getUIManager();
final BasicPluginViewModel model = ui_manager.createBasicPluginViewModel(PLUGIN_RESOURCE_ID);
model.setConfigSectionID(PLUGIN_CONFIGSECTION_ID);
BasicPluginConfigModel config = ui_manager.createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, PLUGIN_CONFIGSECTION_ID);
config.addLabelParameter2("dht.info");
final BooleanParameter enabled_param = config.addBooleanParameter2("dht.enabled", "dht.enabled", true);
plugin_interface.getPluginconfig().addListener(new PluginConfigListener() {
@Override
public void configSaved() {
int new_dht_data_port = UDPNetworkManager.getSingleton().getUDPNonDataListeningPortNumber();
if (new_dht_data_port != dht_data_port) {
changePort(new_dht_data_port);
}
}
});
LabelParameter reseed_label = config.addLabelParameter2("dht.reseed.label");
final StringParameter reseed_ip = config.addStringParameter2("dht.reseed.ip", "dht.reseed.ip", "");
final IntParameter reseed_port = config.addIntParameter2("dht.reseed.port", "dht.reseed.port", 0);
reseed = config.addActionParameter2("dht.reseed.info", "dht.reseed");
reseed.setEnabled(false);
config.createGroup("dht.reseed.group", new Parameter[] { reseed_label, reseed_ip, reseed_port, reseed });
final BooleanParameter ipfilter_logging_param = config.addBooleanParameter2("dht.ipfilter.log", "dht.ipfilter.log", true);
ipfilter_logging[0] = ipfilter_logging_param.getValue();
ipfilter_logging_param.addListener(new ParameterListener() {
@Override
public void parameterChanged(Parameter p) {
ipfilter_logging[0] = ipfilter_logging_param.getValue();
}
});
warn_user = config.addBooleanParameter2("dht.warn.user", "dht.warn.user", true);
prefer_i2p = config.addBooleanParameter2("dht.prefer.i2p", "dht.prefer.i2p", false);
BooleanParameter sleeping = config.addBooleanParameter2("dht.is.sleeping", "dht.is.sleeping", false);
AERunStateHandler.addListener(new AERunStateHandler.RunStateChangeListener() {
@Override
public void runStateChanged(long run_state) {
sleeping.setValue(AERunStateHandler.isDHTSleeping());
}
}, true);
sleeping.addListener(new ParameterListener() {
@Override
public void parameterChanged(Parameter param) {
AERunStateHandler.setDHTSleeping(sleeping.getValue());
}
});
final BooleanParameter advanced = config.addBooleanParameter2("dht.advanced", "dht.advanced", false);
LabelParameter advanced_label = config.addLabelParameter2("dht.advanced.label");
final StringParameter override_ip = config.addStringParameter2("dht.override.ip", "dht.override.ip", "");
config.createGroup("dht.advanced.group", new Parameter[] { advanced_label, override_ip });
advanced.addEnabledOnSelection(advanced_label);
advanced.addEnabledOnSelection(override_ip);
final StringParameter command = config.addStringParameter2("dht.execute.command", "dht.execute.command", "print");
ActionParameter execute = config.addActionParameter2("dht.execute.info", "dht.execute");
final BooleanParameter logging = config.addBooleanParameter2("dht.logging", "dht.logging", false);
config.createGroup("dht.diagnostics.group", new Parameter[] { command, execute, logging });
logging.addListener(new ParameterListener() {
@Override
public void parameterChanged(Parameter param) {
if (dhts != null) {
for (int i = 0; i < dhts.length; i++) {
dhts[i].setLogging(logging.getValue());
}
}
}
});
final DHTPluginOperationListener log_polistener = new DHTPluginOperationListener() {
@Override
public boolean diversified() {
return (true);
}
@Override
public void starts(byte[] key) {
}
@Override
public void valueRead(DHTPluginContact originator, DHTPluginValue value) {
log.log("valueRead: " + new String(value.getValue()) + " from " + originator.getName() + "/" + originator.getAddress() + ", flags=" + Integer.toHexString(value.getFlags() & 0x00ff));
if ((value.getFlags() & DHTPlugin.FLAG_STATS) != 0) {
DHTPluginKeyStats stats = decodeStats(value);
log.log(" stats: size=" + (stats == null ? "null" : stats.getSize()));
}
}
@Override
public void valueWritten(DHTPluginContact target, DHTPluginValue value) {
log.log("valueWritten:" + new String(value.getValue()) + " to " + target.getName() + "/" + target.getAddress());
}
@Override
public void complete(byte[] key, boolean timeout_occurred) {
log.log("complete: timeout = " + timeout_occurred);
}
};
execute.addListener(new ParameterListener() {
@Override
public void parameterChanged(Parameter param) {
AEThread2 t = new AEThread2("DHT:commandrunner", true) {
@Override
public void run() {
try {
if (dhts == null) {
return;
}
String c = command.getValue().trim();
String lc = c.toLowerCase();
if (lc.equals("suspend")) {
if (!setSuspended(true)) {
Debug.out("Suspend failed");
}
return;
} else if (lc.equals("resume")) {
if (!setSuspended(false)) {
Debug.out("Resume failed");
}
return;
} else if (lc.equals("bridge_put")) {
try {
List<DistributedDatabase> ddbs = plugin_interface.getUtilities().getDistributedDatabases(new String[] { AENetworkClassifier.AT_I2P });
DistributedDatabase ddb = ddbs.get(0);
DistributedDatabaseKey key = ddb.createKey("fred");
key.setFlags(DistributedDatabaseKey.FL_BRIDGED);
ddb.write(new DistributedDatabaseListener() {
@Override
public void event(DistributedDatabaseEvent event) {
// TODO Auto-generated method stub
}
}, key, ddb.createValue("bill"));
} catch (Throwable e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < dhts.length; i++) {
DHT dht = dhts[i].getDHT();
DHTTransportUDP transport = (DHTTransportUDP) dht.getTransport();
if (lc.equals("print")) {
dht.print(true);
dhts[i].logStats();
} else if (lc.equals("pingall")) {
if (i == 1) {
dht.getControl().pingAll();
}
} else if (lc.equals("versions")) {
List<DHTRouterContact> contacts = dht.getRouter().getAllContacts();
Map<Byte, Integer> counts = new TreeMap<>();
for (DHTRouterContact r : contacts) {
DHTControlContact contact = (DHTControlContact) r.getAttachment();
byte v = contact.getTransportContact().getProtocolVersion();
Integer count = counts.get(v);
if (count == null) {
counts.put(v, 1);
} else {
counts.put(v, count + 1);
}
}
log.log("Net " + dht.getTransport().getNetwork());
int total = contacts.size();
if (total == 0) {
log.log(" no contacts");
} else {
String ver = "";
for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
ver += (ver.length() == 0 ? "" : ", ") + entry.getKey() + "=" + 100 * entry.getValue() / total + "%";
}
log.log(" contacts=" + total + ": " + ver);
}
} else if (lc.equals("testca")) {
((DHTTransportUDPImpl) transport).testExternalAddressChange();
} else if (lc.equals("testnd")) {
((DHTTransportUDPImpl) transport).testNetworkAlive(false);
} else if (lc.equals("testna")) {
((DHTTransportUDPImpl) transport).testNetworkAlive(true);
} else {
int pos = c.indexOf(' ');
if (pos != -1) {
String lhs = lc.substring(0, pos);
String rhs = c.substring(pos + 1);
if (lhs.equals("set")) {
pos = rhs.indexOf('=');
if (pos != -1) {
DHTPlugin.this.put(rhs.substring(0, pos).getBytes(), "DHT Plugin: set", rhs.substring(pos + 1).getBytes(), (byte) 0, log_polistener);
}
} else if (lhs.equals("get")) {
DHTPlugin.this.get(rhs.getBytes("UTF-8"), "DHT Plugin: get", (byte) 0, 1, 10000, true, false, log_polistener);
} else if (lhs.equals("query")) {
DHTPlugin.this.get(rhs.getBytes("UTF-8"), "DHT Plugin: get", DHTPlugin.FLAG_STATS, 1, 10000, true, false, log_polistener);
} else if (lhs.equals("punch")) {
Map originator_data = new HashMap();
originator_data.put("hello", "mum");
DHTNATPuncher puncher = dht.getNATPuncher();
if (puncher != null) {
puncher.punch("Test", transport.getLocalContact(), null, originator_data);
}
} else if (lhs.equals("stats")) {
try {
pos = rhs.lastIndexOf(":");
DHTTransportContact contact;
if (pos == -1) {
contact = transport.getLocalContact();
} else {
String host = rhs.substring(0, pos);
int port = Integer.parseInt(rhs.substring(pos + 1));
contact = transport.importContact(new InetSocketAddress(host, port), transport.getProtocolVersion(), false);
}
log.log("Stats request to " + contact.getName());
DHTTransportFullStats stats = contact.getStats();
log.log("Stats:" + (stats == null ? "<null>" : stats.getString()));
DHTControlActivity[] activities = dht.getControl().getActivities();
for (int j = 0; j < activities.length; j++) {
log.log(" act:" + activities[j].getString());
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
}
}
} catch (Throwable e) {
Debug.out(e);
}
}
};
t.start();
}
});
reseed.addListener(new ParameterListener() {
@Override
public void parameterChanged(Parameter param) {
reseed.setEnabled(false);
AEThread2 t = new AEThread2("DHT:reseeder", true) {
@Override
public void run() {
try {
String ip = reseed_ip.getValue().trim();
if (dhts == null) {
return;
}
int port = reseed_port.getValue();
for (int i = 0; i < dhts.length; i++) {
DHTPluginImpl dht = dhts[i];
if (ip.length() == 0 || port == 0) {
dht.checkForReSeed(true);
} else {
DHTTransportContact seed = dht.importSeed(ip, port);
if (seed != null) {
dht.integrateDHT(false, seed);
}
}
}
} finally {
reseed.setEnabled(true);
}
}
};
t.start();
}
});
model.getActivity().setVisible(false);
model.getProgress().setVisible(false);
log.addListener(new LoggerChannelListener() {
@Override
public void messageLogged(int type, String message) {
model.getLogArea().appendText(message + "\n");
}
@Override
public void messageLogged(String str, Throwable error) {
model.getLogArea().appendText(error.toString() + "\n");
}
});
dht_log = new DHTLogger() {
@Override
public void log(String str) {
log.log(str);
}
@Override
public void log(Throwable e) {
log.log(e);
}
@Override
public void log(int log_type, String str) {
if (isEnabled(log_type)) {
log.log(str);
}
}
@Override
public boolean isEnabled(int log_type) {
if (log_type == DHTLogger.LT_IP_FILTER) {
return ipfilter_logging[0];
}
return (true);
}
@Override
public PluginInterface getPluginInterface() {
return (log.getLogger().getPluginInterface());
}
};
if (!enabled_param.getValue()) {
model.getStatus().setText("Disabled");
status = STATUS_DISABLED;
init_sem.releaseForever();
return;
}
setPluginInfo();
plugin_interface.addListener(new PluginListener() {
@Override
public void initializationComplete() {
PluginInterface pi_upnp = plugin_interface.getPluginManager().getPluginInterfaceByClass(UPnPPlugin.class);
if (pi_upnp == null) {
log.log("UPnP plugin not found, can't map port");
} else {
upnp_mapping = ((UPnPPlugin) pi_upnp.getPlugin()).addMapping(plugin_interface.getPluginName(), false, dht_data_port, true);
}
String ip = null;
if (advanced.getValue()) {
ip = override_ip.getValue().trim();
if (ip.length() == 0) {
ip = null;
}
}
initComplete(model.getStatus(), logging.getValue(), ip);
}
@Override
public void closedownInitiated() {
if (dhts != null) {
for (int i = 0; i < dhts.length; i++) {
dhts[i].closedownInitiated();
}
}
saveClockSkew();
}
@Override
public void closedownComplete() {
}
});
final int sample_frequency = 60 * 1000;
// every 15 mins
final int sample_stats_ticks = 15;
plugin_interface.getUtilities().createTimer("DHTStats", true).addPeriodicEvent(sample_frequency, new UTTimerEventPerformer() {
@Override
public void perform(UTTimerEvent event) {
if (dhts != null) {
for (int i = 0; i < dhts.length; i++) {
dhts[i].updateStats(sample_stats_ticks);
}
}
setPluginInfo();
saveClockSkew();
}
});
}
use of com.biglybt.plugin.upnp.UPnPPlugin in project BiglyBT by BiglySoftware.
the class PairingManagerImpl method doUpdate.
protected void doUpdate() {
long now = SystemTime.getMonotonousTime();
synchronized (this) {
if (deferred_update_event != null) {
return;
}
long time_since_last_update = now - last_update_time;
if (last_update_time > 0 && time_since_last_update < min_update_period) {
deferUpdate(min_update_period - time_since_last_update);
return;
}
update_in_progress = true;
}
try {
Map<String, Object> payload = new HashMap<>();
boolean is_enabled = param_enable.getValue();
boolean has_services = false;
synchronized (this) {
List<Map<String, String>> list = new ArrayList<>();
payload.put("s", list);
if (services.size() > 0 && is_enabled) {
if (global_update_event == null) {
global_update_event = SimpleTimer.addPeriodicEvent("PM:updater", GLOBAL_UPDATE_PERIOD, new TimerEventPerformer() {
private int tick_count;
@Override
public void perform(TimerEvent event) {
tick_count++;
updateGlobals(false);
if (tick_count % CD_REFRESH_TICKS == 0) {
updateNeeded();
}
}
});
updateGlobals(true);
}
boolean enable_nets = param_net_enable.getValue();
for (PairedServiceImpl service : services.values()) {
list.add(service.toMap(enable_nets));
}
has_services = list.size() > 0;
} else {
if (global_update_event == null) {
if (consec_update_fails == 0 && !must_update_once) {
update_in_progress = false;
setStatus(MessageText.getString(is_enabled ? "pairing.status.noservices" : "label.disabled"));
return;
}
} else {
global_update_event.cancel();
global_update_event = null;
}
}
last_update_time = now;
}
// we need a valid access code here!
String ac = readAccessCode();
if (ac.length() == 0) {
ac = allocateAccessCode(true);
}
payload.put("ac", ac);
String gc = getGroup();
if (gc != null && gc.length() > 0) {
payload.put("gc", gc);
}
if (is_enabled && has_services && param_srp_enable.getValue()) {
tunnel_handler.setActive(true);
tunnel_handler.updateRegistrationData(payload);
} else {
tunnel_handler.setActive(false);
}
synchronized (this) {
if (current_v4 != null) {
payload.put("c_v4", current_v4.getHostAddress());
}
if (current_v6 != null) {
payload.put("c_v6", current_v6.getHostAddress());
}
if (local_v4.length() > 0) {
payload.put("l_v4", local_v4);
}
if (local_v6.length() > 0) {
payload.put("l_v6", local_v6);
}
if (param_e_enable.getValue()) {
String host = param_host.getValue().trim();
if (host.length() > 0) {
payload.put("e_h", host);
}
String v4 = param_public_ipv4.getValue().trim();
if (v4.length() > 0) {
payload.put("e_v4", v4);
}
String v6 = param_public_ipv6.getValue().trim();
if (v6.length() > 0) {
payload.put("e_v6", v6);
}
String l_v4 = param_local_ipv4.getValue().trim();
if (l_v4.length() > 0) {
payload.put("e_l_v4", l_v4);
}
String l_v6 = param_local_ipv6.getValue().trim();
if (l_v6.length() > 0) {
payload.put("e_l_v6", l_v6);
}
}
try {
PluginInterface pi_upnp = core.getPluginManager().getPluginInterfaceByClass(UPnPPlugin.class);
if (pi_upnp != null) {
UPnPPlugin upnp = (UPnPPlugin) pi_upnp.getPlugin();
if (upnp.isEnabled()) {
List<Map<String, String>> upnp_list = new ArrayList<>();
payload.put("upnp", upnp_list);
UPnPPluginService[] services = upnp.getServices();
Set<UPnPRootDevice> devices = new HashSet<>();
for (UPnPPluginService service : services) {
if (upnp_list.size() > 10) {
break;
}
UPnPRootDevice root_device = service.getService().getGenericService().getDevice().getRootDevice();
if (!devices.contains(root_device)) {
devices.add(root_device);
Map<String, String> map = new HashMap<>();
upnp_list.add(map);
map.put("i", root_device.getInfo());
}
}
}
}
} catch (Throwable e) {
}
try {
NetworkAdmin admin = NetworkAdmin.getSingleton();
NetworkAdminHTTPProxy http_proxy = admin.getHTTPProxy();
if (http_proxy != null) {
payload.put("hp", http_proxy.getName());
}
NetworkAdminSocksProxy[] socks_proxies = admin.getSocksProxies();
if (socks_proxies.length > 0) {
payload.put("sp", socks_proxies[0].getName());
}
} catch (Throwable e) {
}
payload.put("_enabled", is_enabled ? 1L : 0L);
}
if (DEBUG) {
System.out.println("PS: doUpdate: " + payload);
}
sendRequest("update", payload);
synchronized (this) {
consec_update_fails = 0;
must_update_once = false;
if (deferred_update_event == null) {
COConfigurationManager.setParameter("pairing.updateoutstanding", false);
}
update_in_progress = false;
if (global_update_event == null) {
setStatus(MessageText.getString(is_enabled ? "pairing.status.noservices" : "label.disabled"));
} else {
setStatus(MessageText.getString("pairing.status.registered", new String[] { new SimpleDateFormat().format(new Date(SystemTime.getCurrentTime())) }));
}
}
} catch (Throwable e) {
synchronized (this) {
try {
consec_update_fails++;
long back_off = min_update_period;
for (int i = 0; i < consec_update_fails; i++) {
back_off *= 2;
if (back_off > max_update_period) {
back_off = max_update_period;
break;
}
}
deferUpdate(back_off);
} finally {
update_in_progress = false;
}
}
} finally {
synchronized (this) {
if (update_in_progress) {
Debug.out("Something didn't clear update_in_progress!!!!");
update_in_progress = false;
}
}
}
}
Aggregations