propagate from branch 'i2p.i2p.zzz.upnp' (head 348acc252da725bc621791ef811a43943e889833)
to branch 'i2p.i2p' (head 264d0119a37e276dce2996f360f9c8e065b30008)
This commit is contained in:
12
LICENSE.txt
12
LICENSE.txt
@ -67,7 +67,17 @@ Public domain except as listed below:
|
||||
|
||||
|
||||
Router:
|
||||
Public domain
|
||||
Public domain except as listed below:
|
||||
UPnP.java:
|
||||
From freenet
|
||||
See licenses/LICENSE-GPLv2.txt
|
||||
|
||||
UPnP subsystem:
|
||||
Copyright (C) 2003-2006 Satoshi Konno
|
||||
See licenses/LICENSE-UPnP.txt
|
||||
|
||||
XMLPull library used by UPnP:
|
||||
See licenses/LICENSE-Apache2.0.txt
|
||||
|
||||
|
||||
|
||||
|
@ -4,6 +4,7 @@ import net.i2p.data.RouterInfo;
|
||||
import net.i2p.router.LoadTestManager;
|
||||
import net.i2p.router.Router;
|
||||
import net.i2p.router.transport.FIFOBandwidthRefiller;
|
||||
import net.i2p.router.transport.TransportManager;
|
||||
import net.i2p.router.transport.udp.UDPTransport;
|
||||
import net.i2p.router.web.ConfigServiceHandler.UpdateWrapperManagerAndRekeyTask;
|
||||
import net.i2p.time.Timestamper;
|
||||
@ -25,9 +26,13 @@ public class ConfigNetHandler extends FormHandler {
|
||||
private String _ntcpHostname;
|
||||
private String _ntcpPort;
|
||||
private String _tcpPort;
|
||||
private String _udpHost1;
|
||||
private String _udpHost2;
|
||||
private String _udpPort;
|
||||
private boolean _ntcpAutoIP;
|
||||
private String _udpAutoIP;
|
||||
private String _ntcpAutoIP;
|
||||
private boolean _ntcpAutoPort;
|
||||
private boolean _upnp;
|
||||
private String _inboundRate;
|
||||
private String _inboundBurstRate;
|
||||
private String _inboundBurst;
|
||||
@ -37,7 +42,8 @@ public class ConfigNetHandler extends FormHandler {
|
||||
private String _reseedFrom;
|
||||
private boolean _enableLoadTesting;
|
||||
private String _sharePct;
|
||||
private boolean _ratesOnly;
|
||||
private static final boolean _ratesOnly = false; // always false - delete me
|
||||
private static final String PROP_HIDDEN = Router.PROP_HIDDEN_HIDDEN; // see Router for other choice
|
||||
|
||||
protected void processForm() {
|
||||
if (_saveRequested || ( (_action != null) && ("Save changes".equals(_action)) )) {
|
||||
@ -53,12 +59,19 @@ public class ConfigNetHandler extends FormHandler {
|
||||
public void setEnabletimesync(String moo) { _timeSyncEnabled = true; }
|
||||
public void setRecheckReachability(String moo) { _recheckReachabilityRequested = true; }
|
||||
public void setRequireIntroductions(String moo) { _requireIntroductions = true; }
|
||||
public void setHiddenMode(String moo) { _hiddenMode = true; }
|
||||
public void setDynamicKeys(String moo) { _dynamicKeys = true; }
|
||||
public void setUpdateratesonly(String moo) { _ratesOnly = true; }
|
||||
public void setEnableloadtesting(String moo) { _enableLoadTesting = true; }
|
||||
public void setNtcpAutoIP(String moo) { _ntcpAutoIP = true; }
|
||||
public void setNtcpAutoPort(String moo) { _ntcpAutoPort = true; }
|
||||
public void setUdpAutoIP(String mode) {
|
||||
_udpAutoIP = mode;
|
||||
_hiddenMode = "hidden".equals(mode);
|
||||
}
|
||||
public void setNtcpAutoIP(String mode) {
|
||||
_ntcpAutoIP = mode;
|
||||
}
|
||||
public void setNtcpAutoPort(String mode) {
|
||||
_ntcpAutoPort = mode.equals("2");
|
||||
}
|
||||
public void setUpnp(String moo) { _upnp = true; }
|
||||
|
||||
public void setHostname(String hostname) {
|
||||
_hostname = (hostname != null ? hostname.trim() : null);
|
||||
@ -72,6 +85,12 @@ public class ConfigNetHandler extends FormHandler {
|
||||
public void setNtcpport(String port) {
|
||||
_ntcpPort = (port != null ? port.trim() : null);
|
||||
}
|
||||
public void setUdpHost1(String host) {
|
||||
_udpHost1 = (host != null ? host.trim() : null);
|
||||
}
|
||||
public void setUdpHost2(String host) {
|
||||
_udpHost2 = (host != null ? host.trim() : null);
|
||||
}
|
||||
public void setUdpPort(String port) {
|
||||
_udpPort = (port != null ? port.trim() : null);
|
||||
}
|
||||
@ -111,58 +130,75 @@ public class ConfigNetHandler extends FormHandler {
|
||||
boolean restartRequired = false;
|
||||
|
||||
if (!_ratesOnly) {
|
||||
// IP Settings
|
||||
String oldUdp = _context.getProperty(UDPTransport.PROP_SOURCES, UDPTransport.DEFAULT_SOURCES);
|
||||
String oldUHost = _context.getProperty(UDPTransport.PROP_EXTERNAL_HOST, "");
|
||||
if (_udpAutoIP != null) {
|
||||
String uhost = "";
|
||||
if (_udpAutoIP.equals("fixed")) {
|
||||
if (_udpHost1 != null && _udpHost1.length() > 0)
|
||||
uhost = _udpHost1;
|
||||
else if (_udpHost2 != null && _udpHost2.length() > 0)
|
||||
uhost = _udpHost2;
|
||||
else
|
||||
_udpAutoIP = UDPTransport.DEFAULT_SOURCES;
|
||||
}
|
||||
_context.router().setConfigSetting(UDPTransport.PROP_SOURCES, _udpAutoIP);
|
||||
// Todo: Catch local IPs right here rather than complaining later
|
||||
_context.router().setConfigSetting(UDPTransport.PROP_EXTERNAL_HOST, uhost);
|
||||
if ((!oldUdp.equals(_udpAutoIP)) || (!oldUHost.equals(uhost))) {
|
||||
addFormNotice("Updating IP address");
|
||||
restartRequired = true;
|
||||
}
|
||||
}
|
||||
|
||||
// NTCP Settings
|
||||
// Normalize some things to make the following code a little easier...
|
||||
String oldNHost = _context.router().getConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_HOSTNAME);
|
||||
if (oldNHost == null) oldNHost = "";
|
||||
String oldNPort = _context.router().getConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_PORT);
|
||||
if (oldNPort == null) oldNPort = "";
|
||||
String sAutoHost = _context.router().getConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_IP);
|
||||
String sAutoPort = _context.router().getConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_PORT);
|
||||
boolean oldAutoHost = "true".equalsIgnoreCase(sAutoHost);
|
||||
String oldNHost = _context.getProperty(ConfigNetHelper.PROP_I2NP_NTCP_HOSTNAME, "");
|
||||
String oldNPort = _context.getProperty(ConfigNetHelper.PROP_I2NP_NTCP_PORT, "");
|
||||
String oldAutoHost = _context.getProperty(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_IP, "true");
|
||||
String sAutoPort = _context.getProperty(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_PORT, "true");
|
||||
boolean oldAutoPort = "true".equalsIgnoreCase(sAutoPort);
|
||||
if (_ntcpHostname == null) _ntcpHostname = "";
|
||||
if (_ntcpPort == null) _ntcpPort = "";
|
||||
if (_ntcpAutoIP == null) _ntcpAutoIP = "true";
|
||||
|
||||
if (oldAutoHost != _ntcpAutoIP || ! oldNHost.equalsIgnoreCase(_ntcpHostname)) {
|
||||
if (_ntcpAutoIP) {
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_IP, "true");
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_HOSTNAME);
|
||||
addFormNotice("Updating inbound TCP address to auto");
|
||||
} else if (_ntcpHostname.length() > 0) {
|
||||
if ((!oldAutoHost.equals(_ntcpAutoIP)) || ! oldNHost.equalsIgnoreCase(_ntcpHostname)) {
|
||||
if ("disabled".equals(_ntcpAutoIP)) {
|
||||
addFormNotice("Disabling TCP completely");
|
||||
} else if ("false".equals(_ntcpAutoIP) && _ntcpHostname.length() > 0) {
|
||||
// Todo: Catch local IPs right here rather than complaining later
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_HOSTNAME, _ntcpHostname);
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_IP);
|
||||
addFormNotice("Updating inbound TCP address to " + _ntcpHostname);
|
||||
} else {
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_HOSTNAME);
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_IP);
|
||||
addFormNotice("Disabling inbound TCP");
|
||||
if ("false".equals(_ntcpAutoIP))
|
||||
addFormNotice("Disabling inbound TCP");
|
||||
else
|
||||
addFormNotice("Updating inbound TCP address to auto"); // true or always
|
||||
}
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_IP, _ntcpAutoIP);
|
||||
_context.router().setConfigSetting(TransportManager.PROP_ENABLE_NTCP, "" + !"disabled".equals(_ntcpAutoIP));
|
||||
restartRequired = true;
|
||||
}
|
||||
if (oldAutoPort != _ntcpAutoPort || ! oldNPort.equals(_ntcpPort)) {
|
||||
if ( _ntcpAutoPort ) {
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_PORT, "true");
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_PORT);
|
||||
addFormNotice("Updating inbound TCP port to auto");
|
||||
} else if (_ntcpPort.length() > 0) {
|
||||
if (_ntcpPort.length() > 0 && !_ntcpAutoPort) {
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_PORT, _ntcpPort);
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_PORT);
|
||||
addFormNotice("Updating inbound TCP port to " + _ntcpPort);
|
||||
} else {
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_PORT);
|
||||
_context.router().removeConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_PORT);
|
||||
addFormNotice("Disabling inbound TCP");
|
||||
addFormNotice("Updating inbound TCP port to auto");
|
||||
}
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_NTCP_AUTO_PORT, "" + _ntcpAutoPort);
|
||||
restartRequired = true;
|
||||
}
|
||||
|
||||
// UDP Settings
|
||||
if ( (_udpPort != null) && (_udpPort.length() > 0) ) {
|
||||
String oldPort = _context.router().getConfigSetting(ConfigNetHelper.PROP_I2NP_UDP_PORT);
|
||||
if ( (oldPort == null) && (_udpPort.equals("8887")) ) {
|
||||
// still on default.. noop
|
||||
} else if ( (oldPort == null) || (!oldPort.equalsIgnoreCase(_udpPort)) ) {
|
||||
// its not the default OR it has changed
|
||||
_context.router().setConfigSetting(ConfigNetHelper.PROP_I2NP_UDP_PORT, _udpPort);
|
||||
String oldPort = "" + _context.getProperty(UDPTransport.PROP_INTERNAL_PORT, UDPTransport.DEFAULT_INTERNAL_PORT);
|
||||
if (!oldPort.equals(_udpPort)) {
|
||||
_context.router().setConfigSetting(UDPTransport.PROP_INTERNAL_PORT, _udpPort);
|
||||
_context.router().setConfigSetting(UDPTransport.PROP_EXTERNAL_PORT, _udpPort);
|
||||
addFormNotice("Updating UDP port from " + oldPort + " to " + _udpPort);
|
||||
restartRequired = true;
|
||||
}
|
||||
@ -172,36 +208,29 @@ public class ConfigNetHandler extends FormHandler {
|
||||
|
||||
updateRates();
|
||||
|
||||
boolean switchRequired = false;
|
||||
if (!_ratesOnly) {
|
||||
if (_sharePct != null) {
|
||||
String old = _context.router().getConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE);
|
||||
if ( (old == null) || (!old.equalsIgnoreCase(_sharePct)) ) {
|
||||
_context.router().setConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE, _sharePct);
|
||||
addFormNotice("Updating bandwidth share percentage");
|
||||
}
|
||||
}
|
||||
|
||||
// If hidden mode value changes, restart is required
|
||||
if (_hiddenMode && "false".equalsIgnoreCase(_context.getProperty(Router.PROP_HIDDEN, "false"))) {
|
||||
_context.router().setConfigSetting(Router.PROP_HIDDEN, "true");
|
||||
_context.router().addCapabilities(_context.router().getRouterInfo());
|
||||
addFormNotice("Gracefully restarting into Hidden Router Mode. Make sure you have no 0-1 length "
|
||||
switchRequired = _hiddenMode != _context.router().isHidden();
|
||||
if (switchRequired) {
|
||||
_context.router().setConfigSetting(PROP_HIDDEN, "" + _hiddenMode);
|
||||
if (_hiddenMode)
|
||||
addFormNotice("Gracefully restarting into Hidden Router Mode. Make sure you have no 0-1 length "
|
||||
+ "<a href=\"configtunnels.jsp\">tunnels!</a>");
|
||||
hiddenSwitch();
|
||||
else
|
||||
addFormNotice("Gracefully restarting to exit Hidden Router Mode");
|
||||
}
|
||||
|
||||
if (!_hiddenMode && "true".equalsIgnoreCase(_context.getProperty(Router.PROP_HIDDEN, "false"))) {
|
||||
_context.router().removeConfigSetting(Router.PROP_HIDDEN);
|
||||
_context.router().getRouterInfo().delCapability(RouterInfo.CAPABILITY_HIDDEN);
|
||||
addFormNotice("Gracefully restarting to exit Hidden Router Mode");
|
||||
hiddenSwitch();
|
||||
}
|
||||
_context.router().setConfigSetting(Router.PROP_DYNAMIC_KEYS, "" + _dynamicKeys);
|
||||
|
||||
if (_dynamicKeys) {
|
||||
_context.router().setConfigSetting(Router.PROP_DYNAMIC_KEYS, "true");
|
||||
} else {
|
||||
_context.router().removeConfigSetting(Router.PROP_DYNAMIC_KEYS);
|
||||
if (Boolean.valueOf(_context.getProperty(TransportManager.PROP_ENABLE_UPNP)).booleanValue() !=
|
||||
_upnp) {
|
||||
if (_upnp)
|
||||
addFormNotice("Enabling UPnP, restart required to take effect");
|
||||
else
|
||||
addFormNotice("Disabling UPnP, restart required to take effect");
|
||||
}
|
||||
_context.router().setConfigSetting(TransportManager.PROP_ENABLE_UPNP, "" + _upnp);
|
||||
|
||||
if (_requireIntroductions) {
|
||||
_context.router().setConfigSetting(UDPTransport.PROP_FORCE_INTRODUCERS, "true");
|
||||
@ -210,12 +239,8 @@ public class ConfigNetHandler extends FormHandler {
|
||||
_context.router().removeConfigSetting(UDPTransport.PROP_FORCE_INTRODUCERS);
|
||||
}
|
||||
|
||||
if (true || _timeSyncEnabled) {
|
||||
// Time sync enable, means NOT disabled
|
||||
_context.router().setConfigSetting(Timestamper.PROP_DISABLED, "false");
|
||||
} else {
|
||||
_context.router().setConfigSetting(Timestamper.PROP_DISABLED, "true");
|
||||
}
|
||||
// Time sync enable, means NOT disabled
|
||||
_context.router().setConfigSetting(Timestamper.PROP_DISABLED, "false");
|
||||
|
||||
LoadTestManager.setEnableLoadTesting(_context, _enableLoadTesting);
|
||||
}
|
||||
@ -228,10 +253,17 @@ public class ConfigNetHandler extends FormHandler {
|
||||
addFormNotice("Error saving the configuration (applied but not saved) - please see the error logs");
|
||||
}
|
||||
|
||||
if (restartRequired) {
|
||||
addFormNotice("Performing a soft restart");
|
||||
_context.router().restart();
|
||||
addFormNotice("Soft restart complete");
|
||||
if (switchRequired) {
|
||||
hiddenSwitch();
|
||||
} else if (restartRequired) {
|
||||
//addFormNotice("Performing a soft restart");
|
||||
//_context.router().restart();
|
||||
//addFormNotice("Soft restart complete");
|
||||
// Most of the time we aren't changing addresses, just enabling or disabling
|
||||
// things, so let's try just a new routerInfo and see how that works.
|
||||
// Maybe we should restart if we change addresses though?
|
||||
_context.router().rebuildRouterInfo();
|
||||
addFormNotice("Router Info rebuilt");
|
||||
}
|
||||
}
|
||||
|
||||
@ -243,19 +275,33 @@ public class ConfigNetHandler extends FormHandler {
|
||||
|
||||
private void updateRates() {
|
||||
boolean updated = false;
|
||||
if ( (_inboundRate != null) && (_inboundRate.length() > 0) ) {
|
||||
|
||||
if (_sharePct != null) {
|
||||
String old = _context.router().getConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE);
|
||||
if ( (old == null) || (!old.equalsIgnoreCase(_sharePct)) ) {
|
||||
_context.router().setConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE, _sharePct);
|
||||
addFormNotice("Updating bandwidth share percentage");
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ( (_inboundRate != null) && (_inboundRate.length() > 0) &&
|
||||
!_inboundRate.equals(_context.getProperty(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH, "" + FIFOBandwidthRefiller.DEFAULT_INBOUND_BANDWIDTH))) {
|
||||
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH, _inboundRate);
|
||||
updated = true;
|
||||
}
|
||||
if ( (_outboundRate != null) && (_outboundRate.length() > 0) ) {
|
||||
if ( (_outboundRate != null) && (_outboundRate.length() > 0) &&
|
||||
!_outboundRate.equals(_context.getProperty(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH, "" + FIFOBandwidthRefiller.DEFAULT_OUTBOUND_BANDWIDTH))) {
|
||||
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH, _outboundRate);
|
||||
updated = true;
|
||||
}
|
||||
if ( (_inboundBurstRate != null) && (_inboundBurstRate.length() > 0) ) {
|
||||
if ( (_inboundBurstRate != null) && (_inboundBurstRate.length() > 0) &&
|
||||
!_inboundBurstRate.equals(_context.getProperty(FIFOBandwidthRefiller.PROP_INBOUND_BURST_BANDWIDTH, "" + FIFOBandwidthRefiller.DEFAULT_INBOUND_BURST_BANDWIDTH))) {
|
||||
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BURST_BANDWIDTH, _inboundBurstRate);
|
||||
updated = true;
|
||||
}
|
||||
if ( (_outboundBurstRate != null) && (_outboundBurstRate.length() > 0) ) {
|
||||
if ( (_outboundBurstRate != null) && (_outboundBurstRate.length() > 0) &&
|
||||
!_outboundBurstRate.equals(_context.getProperty(FIFOBandwidthRefiller.PROP_OUTBOUND_BURST_BANDWIDTH, "" + FIFOBandwidthRefiller.DEFAULT_OUTBOUND_BURST_BANDWIDTH))) {
|
||||
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BURST_BANDWIDTH, _outboundBurstRate);
|
||||
updated = true;
|
||||
}
|
||||
@ -296,8 +342,9 @@ public class ConfigNetHandler extends FormHandler {
|
||||
}
|
||||
}
|
||||
|
||||
if (updated && !_ratesOnly)
|
||||
if (updated && !_ratesOnly) {
|
||||
_context.bandwidthLimiter().reinitialize();
|
||||
addFormNotice("Updated bandwidth limits");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,12 @@
|
||||
package net.i2p.router.web;
|
||||
|
||||
import net.i2p.data.DataHelper;
|
||||
import net.i2p.data.RouterAddress;
|
||||
import net.i2p.router.CommSystemFacade;
|
||||
import net.i2p.router.LoadTestManager;
|
||||
import net.i2p.router.Router;
|
||||
import net.i2p.router.RouterContext;
|
||||
import net.i2p.router.transport.Addresses;
|
||||
import net.i2p.router.transport.TransportManager;
|
||||
import net.i2p.router.transport.udp.UDPAddress;
|
||||
import net.i2p.router.transport.udp.UDPTransport;
|
||||
@ -14,25 +16,23 @@ public class ConfigNetHelper extends HelperBase {
|
||||
public ConfigNetHelper() {}
|
||||
|
||||
/** copied from various private components */
|
||||
public final static String PROP_I2NP_UDP_PORT = "i2np.udp.port";
|
||||
public final static String PROP_I2NP_INTERNAL_UDP_PORT = "i2np.udp.internalPort";
|
||||
public final static String PROP_I2NP_NTCP_HOSTNAME = "i2np.ntcp.hostname";
|
||||
public final static String PROP_I2NP_NTCP_PORT = "i2np.ntcp.port";
|
||||
public final static String PROP_I2NP_NTCP_AUTO_PORT = "i2np.ntcp.autoport";
|
||||
public final static String PROP_I2NP_NTCP_AUTO_IP = "i2np.ntcp.autoip";
|
||||
public String getNtcphostname() {
|
||||
if (!TransportManager.enableNTCP(_context))
|
||||
return "\" disabled=\"true";
|
||||
String hostname = _context.getProperty(PROP_I2NP_NTCP_HOSTNAME);
|
||||
if (hostname == null) return "";
|
||||
return hostname;
|
||||
private final static String CHECKED = " checked=\"true\" ";
|
||||
private final static String DISABLED = " disabled=\"true\" ";
|
||||
|
||||
public String getUdphostname() {
|
||||
return _context.getProperty(UDPTransport.PROP_EXTERNAL_HOST, "");
|
||||
}
|
||||
|
||||
public String getNtcphostname() {
|
||||
return _context.getProperty(PROP_I2NP_NTCP_HOSTNAME, "");
|
||||
}
|
||||
|
||||
public String getNtcpport() {
|
||||
if (!TransportManager.enableNTCP(_context))
|
||||
return "\" disabled=\"true";
|
||||
String port = _context.getProperty(PROP_I2NP_NTCP_PORT);
|
||||
if (port == null) return "";
|
||||
return port;
|
||||
return _context.getProperty(PROP_I2NP_NTCP_PORT, "");
|
||||
}
|
||||
|
||||
public String getUdpAddress() {
|
||||
@ -63,75 +63,109 @@ public class ConfigNetHelper extends HelperBase {
|
||||
return "" + ua.getPort();
|
||||
}
|
||||
|
||||
public String getConfiguredUdpPort() {
|
||||
return "" + _context.getProperty(UDPTransport.PROP_INTERNAL_PORT, UDPTransport.DEFAULT_INTERNAL_PORT);
|
||||
}
|
||||
|
||||
public String getEnableTimeSyncChecked() {
|
||||
String disabled = _context.getProperty(Timestamper.PROP_DISABLED, "false");
|
||||
if ( (disabled != null) && ("true".equalsIgnoreCase(disabled)) )
|
||||
return "";
|
||||
else
|
||||
return " checked ";
|
||||
return CHECKED;
|
||||
}
|
||||
|
||||
public String getHiddenModeChecked() {
|
||||
String enabled = _context.getProperty(Router.PROP_HIDDEN, "false");
|
||||
if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) )
|
||||
return " checked ";
|
||||
else
|
||||
return "";
|
||||
/** @param prop must default to false */
|
||||
public String getChecked(String prop) {
|
||||
if (Boolean.valueOf(_context.getProperty(prop)).booleanValue())
|
||||
return CHECKED;
|
||||
return "";
|
||||
}
|
||||
|
||||
public String getDynamicKeysChecked() {
|
||||
String enabled = _context.getProperty(Router.PROP_DYNAMIC_KEYS, "false");
|
||||
if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) )
|
||||
return " checked ";
|
||||
else
|
||||
return "";
|
||||
return getChecked(Router.PROP_DYNAMIC_KEYS);
|
||||
}
|
||||
|
||||
public String getTcpAutoPortChecked() {
|
||||
if (!TransportManager.enableNTCP(_context))
|
||||
return " disabled=\"true\" ";
|
||||
String enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_PORT, "false");
|
||||
if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) )
|
||||
return " checked ";
|
||||
else
|
||||
return "";
|
||||
public String getTcpAutoPortChecked(int mode) {
|
||||
String port = _context.getProperty(PROP_I2NP_NTCP_PORT);
|
||||
boolean specified = port != null && port.length() > 0;
|
||||
if ((mode == 1 && specified) ||
|
||||
(mode == 2 && !specified))
|
||||
return CHECKED;
|
||||
return "";
|
||||
}
|
||||
|
||||
public String getTcpAutoIPChecked() {
|
||||
if (!TransportManager.enableNTCP(_context))
|
||||
return " disabled=\"true\" ";
|
||||
String enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_IP, "false");
|
||||
if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) )
|
||||
return " checked ";
|
||||
else
|
||||
return "";
|
||||
public String getTcpAutoIPChecked(int mode) {
|
||||
boolean enabled = TransportManager.enableNTCP(_context);
|
||||
String hostname = _context.getProperty(PROP_I2NP_NTCP_HOSTNAME);
|
||||
boolean specified = hostname != null && hostname.length() > 0;
|
||||
String auto = _context.getProperty(PROP_I2NP_NTCP_AUTO_IP, "false");
|
||||
if ((mode == 0 && (!specified) && auto.equals("false") && enabled) ||
|
||||
(mode == 1 && specified && auto.equals("false") && enabled) ||
|
||||
(mode == 2 && auto.equals("true") && enabled) ||
|
||||
(mode == 3 && auto.equals("always") && enabled) ||
|
||||
(mode == 4 && !enabled))
|
||||
return CHECKED;
|
||||
return "";
|
||||
}
|
||||
|
||||
public String getUdpAutoIPChecked(int mode) {
|
||||
String hostname = _context.getProperty(UDPTransport.PROP_EXTERNAL_HOST);
|
||||
boolean specified = hostname != null && hostname.length() > 0;
|
||||
boolean hidden = _context.router().isHidden();
|
||||
String sources = _context.getProperty(UDPTransport.PROP_SOURCES, UDPTransport.DEFAULT_SOURCES);
|
||||
if ((mode == 0 && sources.equals("ssu") && !hidden) ||
|
||||
(mode == 1 && specified && !hidden) ||
|
||||
(mode == 2 && hidden) ||
|
||||
(mode == 3 && sources.equals("local,upnp,ssu") && !hidden) ||
|
||||
(mode == 4 && sources.equals("local,ssu") && !hidden) ||
|
||||
(mode == 5 && sources.equals("upnp,ssu") && !hidden))
|
||||
return CHECKED;
|
||||
return "";
|
||||
}
|
||||
|
||||
/** default true */
|
||||
public String getUpnpChecked() {
|
||||
if (Boolean.valueOf(_context.getProperty(TransportManager.PROP_ENABLE_UPNP, "true")).booleanValue())
|
||||
return CHECKED;
|
||||
return "";
|
||||
}
|
||||
|
||||
public String getRequireIntroductionsChecked() {
|
||||
short status = _context.commSystem().getReachabilityStatus();
|
||||
switch (status) {
|
||||
case CommSystemFacade.STATUS_OK:
|
||||
if ("true".equalsIgnoreCase(_context.getProperty(UDPTransport.PROP_FORCE_INTRODUCERS, "false")))
|
||||
return "checked=\"true\"";
|
||||
return "";
|
||||
case CommSystemFacade.STATUS_UNKNOWN:
|
||||
return getChecked(UDPTransport.PROP_FORCE_INTRODUCERS);
|
||||
case CommSystemFacade.STATUS_DIFFERENT:
|
||||
case CommSystemFacade.STATUS_REJECT_UNSOLICITED:
|
||||
return "checked=\"true\"";
|
||||
case CommSystemFacade.STATUS_UNKNOWN:
|
||||
if ("true".equalsIgnoreCase(_context.getProperty(UDPTransport.PROP_FORCE_INTRODUCERS, "false")))
|
||||
return "checked=\"true\"";
|
||||
return "";
|
||||
default:
|
||||
return "checked=\"true\"";
|
||||
return CHECKED;
|
||||
}
|
||||
}
|
||||
|
||||
public String[] getAddresses() {
|
||||
return Addresses.getAddresses();
|
||||
}
|
||||
|
||||
public String getInboundRate() {
|
||||
return "" + _context.bandwidthLimiter().getInboundKBytesPerSecond();
|
||||
}
|
||||
public String getOutboundRate() {
|
||||
return "" + _context.bandwidthLimiter().getOutboundKBytesPerSecond();
|
||||
}
|
||||
public String getInboundRateBits() {
|
||||
return kbytesToBits(_context.bandwidthLimiter().getInboundKBytesPerSecond());
|
||||
}
|
||||
public String getOutboundRateBits() {
|
||||
return kbytesToBits(_context.bandwidthLimiter().getOutboundKBytesPerSecond());
|
||||
}
|
||||
public String getShareRateBits() {
|
||||
return kbytesToBits(getShareBandwidth());
|
||||
}
|
||||
private String kbytesToBits(int kbytes) {
|
||||
return DataHelper.formatSize(kbytes * 8 * 1024) + " bits per second";
|
||||
}
|
||||
public String getInboundBurstRate() {
|
||||
return "" + _context.bandwidthLimiter().getInboundBurstKBytesPerSecond();
|
||||
}
|
||||
@ -182,7 +216,7 @@ public class ConfigNetHelper extends HelperBase {
|
||||
|
||||
public String getEnableLoadTesting() {
|
||||
if (LoadTestManager.isEnabled(_context))
|
||||
return " checked ";
|
||||
return CHECKED;
|
||||
else
|
||||
return "";
|
||||
}
|
||||
@ -190,7 +224,7 @@ public class ConfigNetHelper extends HelperBase {
|
||||
public String getSharePercentageBox() {
|
||||
int pct = (int) (100 * _context.router().getSharePercentage());
|
||||
StringBuffer buf = new StringBuffer(256);
|
||||
buf.append("<select name=\"sharePercentage\">\n");
|
||||
buf.append("<select style=\"text-align: right;\" name=\"sharePercentage\">\n");
|
||||
boolean found = false;
|
||||
for (int i = 30; i <= 110; i += 10) {
|
||||
int val = i;
|
||||
@ -200,12 +234,12 @@ public class ConfigNetHelper extends HelperBase {
|
||||
else
|
||||
val = pct;
|
||||
}
|
||||
buf.append("<option value=\"").append(val).append("\" ");
|
||||
buf.append("<option style=\"text-align: right;\" value=\"").append(val).append("\" ");
|
||||
if (pct == val) {
|
||||
buf.append("selected=\"true\" ");
|
||||
found = true;
|
||||
}
|
||||
buf.append(">Up to ").append(val).append("%</option>\n");
|
||||
buf.append(">").append(val).append("%</option>\n");
|
||||
}
|
||||
buf.append("</select>\n");
|
||||
return buf.toString();
|
||||
|
@ -28,21 +28,31 @@
|
||||
<input type="hidden" name="nonce" value="<%=System.getProperty("net.i2p.router.web.ConfigNetHandler.nonce")%>" />
|
||||
<input type="hidden" name="action" value="blah" />
|
||||
|
||||
<b>Bandwidth limiter</b><br />
|
||||
Inbound rate:
|
||||
<input name="inboundrate" type="text" size="2" value="<jsp:getProperty name="nethelper" property="inboundRate" />" /> KBps
|
||||
<h3>Bandwidth limiter</h3>
|
||||
<p>
|
||||
<b>I2P will work best if you configure your rates to match the speed of your internet connection.</b>
|
||||
</p><p>
|
||||
<table>
|
||||
<tr><td><input style="text-align: right; width: 5em;" name="inboundrate" type="text" size="5" maxlength="5" value="<jsp:getProperty name="nethelper" property="inboundRate" />" /> KBps
|
||||
In <td>(<jsp:getProperty name="nethelper" property="inboundRateBits" />)<br />
|
||||
<!-- let's keep this simple...
|
||||
bursting up to
|
||||
<input name="inboundburstrate" type="text" size="2" value="<jsp:getProperty name="nethelper" property="inboundBurstRate" />" /> KBps for
|
||||
<input name="inboundburstrate" type="text" size="5" value="<jsp:getProperty name="nethelper" property="inboundBurstRate" />" /> KBps for
|
||||
<jsp:getProperty name="nethelper" property="inboundBurstFactorBox" /><br />
|
||||
Outbound rate:
|
||||
<input name="outboundrate" type="text" size="2" value="<jsp:getProperty name="nethelper" property="outboundRate" />" /> KBps
|
||||
-->
|
||||
<tr><td><input style="text-align: right; width: 5em;" name="outboundrate" type="text" size="5" maxlength="5" value="<jsp:getProperty name="nethelper" property="outboundRate" />" /> KBps
|
||||
Out <td>(<jsp:getProperty name="nethelper" property="outboundRateBits" />)<br />
|
||||
<!-- let's keep this simple...
|
||||
bursting up to
|
||||
<input name="outboundburstrate" type="text" size="2" value="<jsp:getProperty name="nethelper" property="outboundBurstRate" />" /> KBps for
|
||||
<jsp:getProperty name="nethelper" property="outboundBurstFactorBox" /><br />
|
||||
<i>KBps = kilobytes per second = 1024 bytes per second = 8192 bits per second.<br />
|
||||
A negative rate sets the default.</i><br />
|
||||
Bandwidth share percentage:
|
||||
<jsp:getProperty name="nethelper" property="sharePercentageBox" /><br />
|
||||
-->
|
||||
<tr><td><jsp:getProperty name="nethelper" property="sharePercentageBox" />
|
||||
Share <td>(<jsp:getProperty name="nethelper" property="shareRateBits" />)<br />
|
||||
</table>
|
||||
</p><p>
|
||||
<% int share = nethelper.getShareBandwidth();
|
||||
if (share < 12) {
|
||||
out.print("<b>NOTE</b>: You have configured I2P to share only " + share + "KBps. ");
|
||||
@ -54,7 +64,7 @@
|
||||
out.print("The higher the share bandwidth the more you improve your anonymity and help the network.<br />");
|
||||
}
|
||||
%>
|
||||
<p>
|
||||
</p><p>
|
||||
<input type="submit" name="save" value="Save changes" /> <input type="reset" value="Cancel" /><br />
|
||||
<hr />
|
||||
<!--
|
||||
@ -67,49 +77,123 @@
|
||||
<a href="oldstats.jsp#test.rtt">test.rtt</a> and related stats.</p>
|
||||
<hr />
|
||||
-->
|
||||
<b>External UDP address:</b> <i><jsp:getProperty name="nethelper" property="udpAddress" /></i><br />
|
||||
<b>Require SSU introductions? </b>
|
||||
<input type="checkbox" name="requireIntroductions" value="true" <jsp:getProperty name="nethelper" property="requireIntroductionsChecked" /> /><br />
|
||||
<p>If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
|
||||
you on your external UDP address. If you can't, I2P now includes supports UDP hole punching
|
||||
with "SSU introductions" - peers who will relay a request from someone you don't know to your
|
||||
router for your router so that you can make an outbound connection to them. I2P will use these
|
||||
introductions automatically if it detects that the port is not forwarded (as shown by
|
||||
the <i>Status: Firewalled</i> line), or you can manually require them here.
|
||||
Users behind symmetric NATs, such as OpenBSD's pf, are not currently supported.</p>
|
||||
<input type="submit" name="recheckReachability" value="Check network reachability..." />
|
||||
<h3>IP and Transport Configuration</h3>
|
||||
<p>
|
||||
<b>Inbound TCP connection configuration:</b><br />
|
||||
Externally reachable hostname or IP address:
|
||||
<input name ="ntcphost" type="text" size="16" value="<jsp:getProperty name="nethelper" property="ntcphostname" />" />
|
||||
(dyndns and the like are fine)<br />
|
||||
OR use IP address detected by SSU
|
||||
(currently <jsp:getProperty name="nethelper" property="udpIP" />)?
|
||||
<input type="checkbox" name="ntcpAutoIP" value="true" <jsp:getProperty name="nethelper" property="tcpAutoIPChecked" /> /><br />
|
||||
<p>
|
||||
Externally reachable TCP port:
|
||||
<input name ="ntcpport" type="text" size="6" value="<jsp:getProperty name="nethelper" property="ntcpport" />" /><br />
|
||||
OR use the same port configured for SSU
|
||||
(currently <jsp:getProperty name="nethelper" property="udpPort" />)?
|
||||
<input type="checkbox" name="ntcpAutoPort" value="true" <jsp:getProperty name="nethelper" property="tcpAutoPortChecked" /> /><br />
|
||||
<p>A hostname entered here will be published in the network database.
|
||||
It is <b>not private</b>.
|
||||
Also, <b>do not enter a private IP address</b> like 127.0.0.1 or 192.168.1.1.
|
||||
</p>
|
||||
<p>You do <i>not</i> need to allow inbound TCP connections - outbound connections work with no
|
||||
configuration. However, if you want to receive inbound TCP connections, you <b>must</b> poke a hole
|
||||
in your NAT or firewall for unsolicited TCP connections. If you specify the wrong IP address or
|
||||
hostname, or do not properly configure your NAT or firewall, your network performance will degrade
|
||||
substantially. When in doubt, leave the hostname and port number blank.</p>
|
||||
<p><b>Note: changing any of these settings will terminate all of your connections and effectively
|
||||
<b>The default settings will work for most people. There is <a href="#chelp">help below</a>.</b>
|
||||
</p><p>
|
||||
<b>UPnP Configuration:</b><br />
|
||||
<input type="checkbox" name="upnp" value="true" <jsp:getProperty name="nethelper" property="upnpChecked" /> />
|
||||
Enable UPnP to open firewall ports - <a href="peers.jsp#upnp">UPnP status</a>
|
||||
</p><p>
|
||||
<b>IP Configuration:</b><br />
|
||||
Externally reachable hostname or IP address:<br />
|
||||
<input type="radio" name="udpAutoIP" value="local,upnp,ssu" <%=nethelper.getUdpAutoIPChecked(3) %> />
|
||||
Use all auto-detect methods<br />
|
||||
<input type="radio" name="udpAutoIP" value="local,ssu" <%=nethelper.getUdpAutoIPChecked(4) %> />
|
||||
Disable UPnP IP address detection<br />
|
||||
<input type="radio" name="udpAutoIP" value="upnp,ssu" <%=nethelper.getUdpAutoIPChecked(5) %> />
|
||||
Ignore local interface IP address<br />
|
||||
<input type="radio" name="udpAutoIP" value="ssu" <%=nethelper.getUdpAutoIPChecked(0) %> />
|
||||
Use SSU IP address detection only<br />
|
||||
<input type="radio" name="udpAutoIP" value="fixed" <%=nethelper.getUdpAutoIPChecked(1) %> />
|
||||
Specify hostname or IP:
|
||||
<input name ="udpHost1" type="text" size="16" value="<jsp:getProperty name="nethelper" property="udphostname" />" />
|
||||
<% String[] ips = nethelper.getAddresses();
|
||||
if (ips.length > 0) {
|
||||
out.print(" or <select name=\"udpHost2\"><option value=\"\" selected=\"true\">Select Interface</option>\n");
|
||||
for (int i = 0; i < ips.length; i++) {
|
||||
out.print("<option value=\"");
|
||||
out.print(ips[i]);
|
||||
out.print("\">");
|
||||
out.print(ips[i]);
|
||||
out.print("</option>\n");
|
||||
}
|
||||
out.print("</select>\n");
|
||||
}
|
||||
%>
|
||||
<br />
|
||||
<input type="radio" name="udpAutoIP" value="hidden" <%=nethelper.getUdpAutoIPChecked(2) %> />
|
||||
Hidden mode - do not publish IP<i>(prevents participating traffic; change restarts router)</i><br />
|
||||
</p><p>
|
||||
<b>UDP Configuration:</b><br />
|
||||
UDP port:
|
||||
<input name ="udpPort" type="text" size="5" maxlength="5" value="<jsp:getProperty name="nethelper" property="configuredUdpPort" />" /><br />
|
||||
<!-- let's keep this simple...
|
||||
<input type="checkbox" name="requireIntroductions" value="true" <jsp:getProperty name="nethelper" property="requireIntroductionsChecked" /> />
|
||||
Require SSU introductions
|
||||
<i>(Enable if you cannot open your firewall)</i>
|
||||
</p><p>
|
||||
Current External UDP address: <i><jsp:getProperty name="nethelper" property="udpAddress" /></i><br />
|
||||
-->
|
||||
</p><p>
|
||||
<b>TCP Configuration:</b><br />
|
||||
Externally reachable hostname or IP address:<br />
|
||||
<input type="radio" name="ntcpAutoIP" value="true" <%=nethelper.getTcpAutoIPChecked(2) %> />
|
||||
Use auto-detected IP address
|
||||
<i>(currently <jsp:getProperty name="nethelper" property="udpIP" />)</i>
|
||||
if we are not firewalled<br />
|
||||
<input type="radio" name="ntcpAutoIP" value="always" <%=nethelper.getTcpAutoIPChecked(3) %> />
|
||||
Always use auto-detected IP address (Not firewalled)<br />
|
||||
<input type="radio" name="ntcpAutoIP" value="false" <%=nethelper.getTcpAutoIPChecked(1) %> />
|
||||
Specify hostname or IP:
|
||||
<input name ="ntcphost" type="text" size="16" value="<jsp:getProperty name="nethelper" property="ntcphostname" />" /><br />
|
||||
<input type="radio" name="ntcpAutoIP" value="false" <%=nethelper.getTcpAutoIPChecked(0) %> />
|
||||
Disable inbound (Firewalled)<br />
|
||||
<input type="radio" name="ntcpAutoIP" value="disabled" <%=nethelper.getTcpAutoIPChecked(4) %> />
|
||||
Completely disable <i>(select only if behind a firewall that throttles or blocks outbound TCP - change requires restart)</i><br />
|
||||
</p><p>
|
||||
Externally reachable TCP port:<br />
|
||||
<input type="radio" name="ntcpAutoPort" value="2" <%=nethelper.getTcpAutoPortChecked(2) %> />
|
||||
Use the same port configured for SSU
|
||||
<i>(currently <jsp:getProperty name="nethelper" property="udpPort" />)</i><br />
|
||||
<input type="radio" name="ntcpAutoPort" value="1" <%=nethelper.getTcpAutoPortChecked(1) %> />
|
||||
Specify Port:
|
||||
<input name ="ntcpport" type="text" size="5" maxlength="5" value="<jsp:getProperty name="nethelper" property="ntcpport" />" /><br />
|
||||
</p><p><b>Note: changing any of these settings will terminate all of your connections and effectively
|
||||
restart your router.</b>
|
||||
</p>
|
||||
<input type="submit" name="save" value="Save changes" /> <input type="reset" value="Cancel" /><br />
|
||||
<hr />
|
||||
<b><a name="chelp">Configuration Help:</a></b>
|
||||
<p>
|
||||
While I2P will work fine behind most firewalls, your speeds and network integration will generally improve
|
||||
if the I2P port (generally 8887) is forwarded for both UDP and TCP.
|
||||
</p><p>
|
||||
If you can, please poke a hole in your firewall to allow unsolicited UDP and TCP packets to reach
|
||||
you. If you can't, I2P supports UPnP (Universal Plug and Play) and UDP hole punching
|
||||
with "SSU introductions" to relay traffic. Most of the options above are for special situations,
|
||||
for example where UPnP does not work correctly, or a firewall not under your control is doing
|
||||
harm. Certain firewalls such as symmetric NATs may not work well with I2P.
|
||||
</p>
|
||||
<!-- let's keep this simple...
|
||||
<input type="submit" name="recheckReachability" value="Check network reachability..." />
|
||||
-->
|
||||
</p><p>
|
||||
UPnP is used to communicate with Internet Gateway Devices (IGDs) to detect the external IP address
|
||||
and forward ports.
|
||||
UPnP support is beta, and may not work for any number of reasons:
|
||||
<ul>
|
||||
<li>No UPnP-compatible device present
|
||||
<li>UPnP disabled on the device
|
||||
<li>Software firewall interference with UPnP
|
||||
<li>Bugs in the device's UPnP implementation
|
||||
<li>Multiple firewall/routers in the internet connection path
|
||||
<li>UPnP device change, reset, or address change
|
||||
</ul>
|
||||
Reviewing the <a href="peers.jsp#upnp">UPnP status</a> may help.
|
||||
UPnP may be enabled or disabled above, but a change requires a router restart to take effect.
|
||||
</p><p>Hostnames entered above will be published in the network database.
|
||||
They are <b>not private</b>.
|
||||
Also, <b>do not enter a private IP address</b> like 127.0.0.1 or 192.168.1.1.
|
||||
If you specify the wrong IP address or
|
||||
hostname, or do not properly configure your NAT or firewall, your network performance will degrade
|
||||
substantially. When in doubt, leave the settings at the defaults.</p>
|
||||
</p>
|
||||
<hr />
|
||||
<b><a name="help">Reachability Help:</a></b>
|
||||
<p>
|
||||
While I2P will work adequately behind a firewall, your speeds and network integration will generally improve
|
||||
if you open up your port (generally 8887) to both UDP and TCP, and enable inbound TCP above.
|
||||
While I2P will work fine behind most firewalls, your speeds and network integration will generally improve
|
||||
if the I2P port (generally 8887) to both UDP and TCP.
|
||||
If you think you have opened up your firewall and I2P still thinks you are firewalled, remember
|
||||
that you may have multiple firewalls, for example both software packages and external hardware routers.
|
||||
If there is an error, the <a href="logs.jsp">logs</a> may also help diagnose the problem.
|
||||
|
@ -1,3 +1,26 @@
|
||||
<center>
|
||||
<h4>
|
||||
<% if (request.getRequestURI().indexOf("config.jsp") != -1) {
|
||||
%>Network<% }
|
||||
else if (request.getRequestURI().indexOf("configservice.jsp") != -1) {
|
||||
%>Service<% }
|
||||
else if (request.getRequestURI().indexOf("configupdate.jsp") != -1) {
|
||||
%>Update<% }
|
||||
else if (request.getRequestURI().indexOf("configtunnels.jsp") != -1) {
|
||||
%>Tunnels<% }
|
||||
else if (request.getRequestURI().indexOf("configclients.jsp") != -1) {
|
||||
%>Clients<% }
|
||||
else if (request.getRequestURI().indexOf("configpeer.jsp") != -1) {
|
||||
%>Peers<% }
|
||||
else if (request.getRequestURI().indexOf("configkeyring.jsp") != -1) {
|
||||
%>Keyring<% }
|
||||
else if (request.getRequestURI().indexOf("configlogging.jsp") != -1) {
|
||||
%>Logging<% }
|
||||
else if (request.getRequestURI().indexOf("configstats.jsp") != -1) {
|
||||
%>Stats<% }
|
||||
else if (request.getRequestURI().indexOf("configadvanced.jsp") != -1) {
|
||||
%>Advanced<% }%>
|
||||
Configuration</h4>
|
||||
<h4><% if (request.getRequestURI().indexOf("config.jsp") != -1) {
|
||||
%>Network | <% } else { %><a href="config.jsp">Network</a> | <% }
|
||||
if (request.getRequestURI().indexOf("configservice.jsp") != -1) {
|
||||
@ -18,3 +41,5 @@
|
||||
%>Stats | <% } else { %><a href="configstats.jsp">Stats</a> | <% }
|
||||
if (request.getRequestURI().indexOf("configadvanced.jsp") != -1) {
|
||||
%>Advanced<% } else { %><a href="configadvanced.jsp">Advanced</a><% } %></h4>
|
||||
</center>
|
||||
<hr />
|
||||
|
@ -1,12 +0,0 @@
|
||||
<%@page contentType="text/html" %>
|
||||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
|
||||
|
||||
<html><head>
|
||||
<title>I2P Router Console - verify update file signature</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- net.i2p.crypto.TrustedUpdate.verify(request.getParameter("filename")) -->
|
||||
|
||||
</body>
|
||||
</html>
|
12
licenses/LICENSE-UPnP.txt
Normal file
12
licenses/LICENSE-UPnP.txt
Normal file
@ -0,0 +1,12 @@
|
||||
Copyright (C) 2003-2006 Satoshi Konno
|
||||
All rights reserved.
|
||||
|
||||
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.
|
@ -61,7 +61,7 @@ public class MessageHistory {
|
||||
}
|
||||
|
||||
void setDoLog(boolean log) { _doLog = log; }
|
||||
boolean getDoLog() { return _doLog; }
|
||||
public boolean getDoLog() { return _doLog; }
|
||||
|
||||
void setPauseFlushes(boolean doPause) { _doPause = doPause; }
|
||||
String getFilename() { return _historyFile; }
|
||||
|
@ -73,7 +73,10 @@ public class Router {
|
||||
/** used to differentiate routerInfo files on different networks */
|
||||
public static final int NETWORK_ID = 2;
|
||||
|
||||
/** this puts an 'H' in your routerInfo **/
|
||||
public final static String PROP_HIDDEN = "router.hiddenMode";
|
||||
/** this does not put an 'H' in your routerInfo **/
|
||||
public final static String PROP_HIDDEN_HIDDEN = "router.isHidden";
|
||||
public final static String PROP_DYNAMIC_KEYS = "router.dynamicKeys";
|
||||
public final static String PROP_INFO_FILENAME = "router.info.location";
|
||||
public final static String PROP_INFO_FILENAME_DEFAULT = "router.info";
|
||||
@ -423,7 +426,7 @@ public class Router {
|
||||
RouterInfo ri = _routerInfo;
|
||||
if ( (ri != null) && (ri.isHidden()) )
|
||||
return true;
|
||||
return Boolean.valueOf(_context.getProperty("router.isHidden", "false")).booleanValue();
|
||||
return Boolean.valueOf(_context.getProperty(PROP_HIDDEN_HIDDEN)).booleanValue();
|
||||
}
|
||||
public Certificate createCertificate() {
|
||||
Certificate cert = new Certificate();
|
||||
|
@ -20,7 +20,7 @@ public class RouterVersion {
|
||||
public final static String VERSION = CoreVersion.VERSION;
|
||||
public final static long BUILD = 0;
|
||||
/** for example "-test" */
|
||||
public final static String EXTRA = "";
|
||||
public final static String EXTRA = "-upnp";
|
||||
public final static String FULL_VERSION = VERSION + "-" + BUILD + EXTRA;
|
||||
public static void main(String args[]) {
|
||||
System.out.println("I2P Router version: " + FULL_VERSION);
|
||||
|
82
router/java/src/net/i2p/router/transport/Addresses.java
Normal file
82
router/java/src/net/i2p/router/transport/Addresses.java
Normal file
@ -0,0 +1,82 @@
|
||||
package net.i2p.router.transport;
|
||||
|
||||
/*
|
||||
* public domain
|
||||
*/
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
/**
|
||||
* Get the local addresses
|
||||
*
|
||||
* @author zzz
|
||||
*/
|
||||
public class Addresses {
|
||||
|
||||
/** return the first non-local address it finds, or null */
|
||||
public static String getAnyAddress() {
|
||||
String[] a = getAddresses();
|
||||
if (a.length > 0)
|
||||
return a[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an array of all addresses, excluding
|
||||
* IPv6, local, broadcast, multicast, etc.
|
||||
*/
|
||||
public static String[] getAddresses() {
|
||||
Set<String> rv = new HashSet(4);
|
||||
try {
|
||||
InetAddress localhost = InetAddress.getLocalHost();
|
||||
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
|
||||
if (allMyIps != null) {
|
||||
for (int i = 0; i < allMyIps.length; i++)
|
||||
add(rv, allMyIps[i]);
|
||||
}
|
||||
} catch (UnknownHostException e) {}
|
||||
|
||||
try {
|
||||
for(Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces(); ifcs.hasMoreElements();) {
|
||||
NetworkInterface ifc = ifcs.nextElement();
|
||||
for(Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) {
|
||||
InetAddress addr = addrs.nextElement();
|
||||
add(rv, addr);
|
||||
}
|
||||
}
|
||||
} catch (SocketException e) {}
|
||||
|
||||
String[] rva = rv.toArray(new String[rv.size()]);
|
||||
Arrays.sort(rva);
|
||||
return rva;
|
||||
}
|
||||
|
||||
private static void add(Set<String> set, InetAddress ia) {
|
||||
if (ia.isAnyLocalAddress() ||
|
||||
ia.isLinkLocalAddress() ||
|
||||
ia.isLoopbackAddress() ||
|
||||
ia.isMulticastAddress() ||
|
||||
ia.isSiteLocalAddress() ||
|
||||
!(ia instanceof Inet4Address)) {
|
||||
// System.err.println("Skipping: " + ia.getHostAddress());
|
||||
return;
|
||||
}
|
||||
String ip = ia.getHostAddress();
|
||||
set.add(ip);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String[] a = getAddresses();
|
||||
for (String s : a)
|
||||
System.err.println("Address: " + s);
|
||||
}
|
||||
}
|
@ -27,6 +27,7 @@ import net.i2p.router.RouterContext;
|
||||
import net.i2p.router.transport.ntcp.NTCPAddress;
|
||||
import net.i2p.router.transport.ntcp.NTCPTransport;
|
||||
import net.i2p.router.transport.udp.UDPAddress;
|
||||
import net.i2p.router.transport.udp.UDPTransport;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
@ -151,8 +152,8 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
|
||||
@Override
|
||||
public short getReachabilityStatus() {
|
||||
if (_manager == null) return CommSystemFacade.STATUS_UNKNOWN;
|
||||
if (_context.router().isHidden()) return CommSystemFacade.STATUS_OK;
|
||||
if (_manager == null) return STATUS_UNKNOWN;
|
||||
if (_context.router().isHidden()) return STATUS_OK;
|
||||
return _manager.getReachabilityStatus();
|
||||
}
|
||||
@Override
|
||||
@ -193,6 +194,9 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
public final static String PROP_I2NP_NTCP_AUTO_PORT = "i2np.ntcp.autoport";
|
||||
public final static String PROP_I2NP_NTCP_AUTO_IP = "i2np.ntcp.autoip";
|
||||
|
||||
/**
|
||||
* This should really be moved to ntcp/NTCPTransport.java, why is it here?
|
||||
*/
|
||||
public static RouterAddress createNTCPAddress(RouterContext ctx) {
|
||||
if (!TransportManager.enableNTCP(ctx)) return null;
|
||||
RouterAddress addr = new RouterAddress();
|
||||
@ -236,12 +240,13 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
|
||||
/**
|
||||
* UDP changed addresses, tell NTCP and restart
|
||||
* This should really be moved to ntcp/NTCPTransport.java, why is it here?
|
||||
*/
|
||||
@Override
|
||||
public void notifyReplaceAddress(RouterAddress UDPAddr) {
|
||||
if (UDPAddr == null)
|
||||
return;
|
||||
NTCPTransport t = (NTCPTransport) _manager.getNTCPTransport();
|
||||
NTCPTransport t = (NTCPTransport) _manager.getTransport(NTCPTransport.STYLE);
|
||||
if (t == null)
|
||||
return;
|
||||
Properties UDPProps = UDPAddr.getOptions();
|
||||
@ -249,7 +254,8 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
return;
|
||||
Properties newProps;
|
||||
RouterAddress oldAddr = t.getCurrentAddress();
|
||||
//_log.warn("Changing NTCP Address? was " + oldAddr);
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Changing NTCP Address? was " + oldAddr);
|
||||
RouterAddress newAddr = oldAddr;
|
||||
if (newAddr == null) {
|
||||
newAddr = new RouterAddress();
|
||||
@ -264,24 +270,51 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
}
|
||||
|
||||
boolean changed = false;
|
||||
|
||||
// Auto Port Setting
|
||||
// old behavior (<= 0.7.3): auto-port defaults to false, and true trumps explicit setting
|
||||
// new behavior (>= 0.7.4): auto-port defaults to true, but explicit setting trumps auto
|
||||
String oport = newProps.getProperty(NTCPAddress.PROP_PORT);
|
||||
String enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_PORT, "false");
|
||||
if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) ) {
|
||||
String nport = UDPProps.getProperty(UDPAddress.PROP_PORT);
|
||||
if (nport == null || nport.length() <= 0)
|
||||
return;
|
||||
if (oport == null || ! oport.equals(nport)) {
|
||||
newProps.setProperty(NTCPAddress.PROP_PORT, nport);
|
||||
changed = true;
|
||||
}
|
||||
} else if (oport == null || oport.length() <= 0) {
|
||||
String nport = null;
|
||||
String cport = _context.getProperty(PROP_I2NP_NTCP_PORT);
|
||||
if (cport != null && cport.length() > 0) {
|
||||
nport = cport;
|
||||
} else if (Boolean.valueOf(_context.getProperty(PROP_I2NP_NTCP_AUTO_PORT, "true")).booleanValue()) {
|
||||
nport = UDPProps.getProperty(UDPAddress.PROP_PORT);
|
||||
}
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("old: " + oport + " config: " + cport + " new: " + nport);
|
||||
if (nport == null || nport.length() <= 0)
|
||||
return;
|
||||
if (oport == null || ! oport.equals(nport)) {
|
||||
newProps.setProperty(NTCPAddress.PROP_PORT, nport);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// Auto IP Setting
|
||||
// old behavior (<= 0.7.3): auto-ip defaults to false, and trumps configured hostname,
|
||||
// and ignores reachability status - leading to
|
||||
// "firewalled with inbound TCP enabled" warnings.
|
||||
// new behavior (>= 0.7.4): auto-ip defaults to true, and explicit setting trumps auto,
|
||||
// and only takes effect if reachability is OK.
|
||||
// And new "always" setting ignores reachability status, like
|
||||
// "true" was in 0.7.3
|
||||
String ohost = newProps.getProperty(NTCPAddress.PROP_HOST);
|
||||
enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_IP, "false");
|
||||
if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) ) {
|
||||
String enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_IP, "true");
|
||||
String name = _context.getProperty(PROP_I2NP_NTCP_HOSTNAME);
|
||||
if (name != null && name.length() > 0)
|
||||
enabled = "false";
|
||||
Transport udp = _manager.getTransport(UDPTransport.STYLE);
|
||||
short status = STATUS_UNKNOWN;
|
||||
if (udp != null)
|
||||
status = udp.getReachabilityStatus();
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("old: " + ohost + " config: " + name + " auto: " + enabled + " status: " + status);
|
||||
if (enabled.equalsIgnoreCase("always") ||
|
||||
(enabled.equalsIgnoreCase("true") && status == STATUS_OK)) {
|
||||
String nhost = UDPProps.getProperty(UDPAddress.PROP_HOST);
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("old: " + ohost + " config: " + name + " new: " + nhost);
|
||||
if (nhost == null || nhost.length() <= 0)
|
||||
return;
|
||||
if (ohost == null || ! ohost.equalsIgnoreCase(nhost)) {
|
||||
@ -293,12 +326,16 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
//_log.warn("No change to NTCP Address");
|
||||
_log.warn("No change to NTCP Address");
|
||||
return;
|
||||
}
|
||||
|
||||
// stopListening stops the pumper, readers, and writers, so required even if
|
||||
// oldAddr == null since startListening starts them all again
|
||||
//
|
||||
// really need to fix this so that we can change or create an inbound address
|
||||
// without tearing down everything
|
||||
//
|
||||
_log.warn("Halting NTCP to change address");
|
||||
t.stopListening();
|
||||
newAddr.setOptions(newProps);
|
||||
|
@ -619,8 +619,8 @@ public class FIFOBandwidthLimiter {
|
||||
public void renderStatusHTML(Writer out) throws IOException {
|
||||
long now = now();
|
||||
StringBuffer buf = new StringBuffer(4096);
|
||||
buf.append("<br /><i id=\"bwlim\">Limiter status: ").append(getStatus().toString()).append("</i><br />\n");
|
||||
buf.append("<b>Pending bandwidth requests:</b><ul>");
|
||||
buf.append("<p><b id=\"bwlim\">Limiter Status:</b><br />").append(getStatus().toString()).append("</p>\n");
|
||||
buf.append("<p><b>Pending bandwidth requests:</b><ul>");
|
||||
buf.append("<li>Inbound requests: <ol>");
|
||||
synchronized (_pendingInboundRequests) {
|
||||
for (int i = 0; i < _pendingInboundRequests.size(); i++) {
|
||||
@ -643,7 +643,7 @@ public class FIFOBandwidthLimiter {
|
||||
buf.append("ms ago</li>\n");
|
||||
}
|
||||
}
|
||||
buf.append("</ol></li></ul>\n");
|
||||
buf.append("</ol></li></ul></p>\n");
|
||||
out.write(buf.toString());
|
||||
out.flush();
|
||||
}
|
||||
|
@ -35,6 +35,12 @@ public interface Transport {
|
||||
public RouterAddress startListening();
|
||||
public void stopListening();
|
||||
public RouterAddress getCurrentAddress();
|
||||
public static final String SOURCE_UPNP = "upnp";
|
||||
public static final String SOURCE_INTERFACE = "local";
|
||||
public static final String SOURCE_CONFIG = "config"; // unused
|
||||
public void externalAddressReceived(String source, byte[] ip, int port);
|
||||
public void forwardPortStatus(int port, boolean success, String reason);
|
||||
public int getRequestedPort();
|
||||
public void setListener(TransportEventListener listener);
|
||||
public String getStyle();
|
||||
|
||||
|
@ -14,4 +14,5 @@ import net.i2p.data.i2np.I2NPMessage;
|
||||
|
||||
public interface TransportEventListener {
|
||||
public void messageReceived(I2NPMessage message, RouterIdentity fromRouter, Hash fromRouterHash);
|
||||
public void transportAddressChanged();
|
||||
}
|
||||
|
@ -416,10 +416,44 @@ public abstract class TransportImpl implements Transport {
|
||||
protected void replaceAddress(RouterAddress address) {
|
||||
// _log.error("Replacing address for " + getStyle() + " was " + _currentAddress + " now " + address);
|
||||
_currentAddress = address;
|
||||
if (_listener != null)
|
||||
_listener.transportAddressChanged();
|
||||
if ("SSU".equals(getStyle()))
|
||||
_context.commSystem().notifyReplaceAddress(address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify a transport of an external address change.
|
||||
* This may be from a local interface, UPnP, a config change, etc.
|
||||
* This should not be called if the ip didn't change
|
||||
* (from that source's point of view), or is a local address,
|
||||
* or if the ip is IPv6, but the transport should check anyway.
|
||||
* The transport should also do its own checking on whether to accept
|
||||
* notifications from this source.
|
||||
*
|
||||
* This can be called before startListening() to set an initial address,
|
||||
* or after the transport is running.
|
||||
*
|
||||
* @param source defined in Transport.java
|
||||
* @param ip typ. IPv4 non-local
|
||||
* @param port 0 for unknown or unchanged
|
||||
*/
|
||||
public void externalAddressReceived(String source, byte[] ip, int port) {}
|
||||
|
||||
/**
|
||||
* Notify a transport of the results of trying to forward a port
|
||||
*/
|
||||
public void forwardPortStatus(int port, boolean success, String reason) {}
|
||||
|
||||
/**
|
||||
* What port would the transport like to have forwarded by UPnP.
|
||||
* This can't be passed via getCurrentAddress(), as we have to open the port
|
||||
* before we can publish the address.
|
||||
*
|
||||
* @return port or -1 for none or 0 for any
|
||||
*/
|
||||
public int getRequestedPort() { return -1; }
|
||||
|
||||
/** Who to notify on message availability */
|
||||
public void setListener(TransportEventListener listener) { _listener = listener; }
|
||||
/** Make this stuff pretty (only used in the old console) */
|
||||
|
@ -10,12 +10,15 @@ package net.i2p.router.transport;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.Vector;
|
||||
@ -35,11 +38,14 @@ public class TransportManager implements TransportEventListener {
|
||||
private Log _log;
|
||||
private List<Transport> _transports;
|
||||
private RouterContext _context;
|
||||
private UPnPManager _upnpManager;
|
||||
|
||||
private final static String PROP_ENABLE_UDP = "i2np.udp.enable";
|
||||
private final static String PROP_ENABLE_NTCP = "i2np.ntcp.enable";
|
||||
private final static String DEFAULT_ENABLE_NTCP = "true";
|
||||
private final static String DEFAULT_ENABLE_UDP = "true";
|
||||
public final static String PROP_ENABLE_UDP = "i2np.udp.enable";
|
||||
public final static String PROP_ENABLE_NTCP = "i2np.ntcp.enable";
|
||||
public final static String DEFAULT_ENABLE_NTCP = "true";
|
||||
public final static String DEFAULT_ENABLE_UDP = "true";
|
||||
/** default true */
|
||||
public final static String PROP_ENABLE_UPNP = "i2np.upnp.enable";
|
||||
|
||||
public TransportManager(RouterContext context) {
|
||||
_context = context;
|
||||
@ -51,6 +57,8 @@ public class TransportManager implements TransportEventListener {
|
||||
_context.statManager().createRateStat("transport.bidFailNoTransports", "Could not attempt to bid on message, as none of the transports could attempt it", "Transport", new long[] { 60*1000, 10*60*1000, 60*60*1000 });
|
||||
_context.statManager().createRateStat("transport.bidFailAllTransports", "Could not attempt to bid on message, as all of the transports had failed", "Transport", new long[] { 60*1000, 10*60*1000, 60*60*1000 });
|
||||
_transports = new ArrayList();
|
||||
if (Boolean.valueOf(_context.getProperty(PROP_ENABLE_UPNP, "true")).booleanValue())
|
||||
_upnpManager = new UPnPManager(context, this);
|
||||
}
|
||||
|
||||
public void addTransport(Transport transport) {
|
||||
@ -71,14 +79,11 @@ public class TransportManager implements TransportEventListener {
|
||||
enableUDP = DEFAULT_ENABLE_UDP;
|
||||
if ("true".equalsIgnoreCase(enableUDP)) {
|
||||
UDPTransport udp = new UDPTransport(_context);
|
||||
udp.setListener(this);
|
||||
_transports.add(udp);
|
||||
}
|
||||
if (enableNTCP(_context)) {
|
||||
NTCPTransport ntcp = new NTCPTransport(_context);
|
||||
ntcp.setListener(this);
|
||||
_transports.add(ntcp);
|
||||
addTransport(udp);
|
||||
initializeAddress(udp);
|
||||
}
|
||||
if (enableNTCP(_context))
|
||||
addTransport(new NTCPTransport(_context));
|
||||
if (_transports.size() <= 0)
|
||||
_log.log(Log.CRIT, "No transports are enabled");
|
||||
}
|
||||
@ -90,14 +95,59 @@ public class TransportManager implements TransportEventListener {
|
||||
return "true".equalsIgnoreCase(enableNTCP);
|
||||
}
|
||||
|
||||
private static void initializeAddress(Transport t) {
|
||||
String ips = Addresses.getAnyAddress();
|
||||
if (ips == null)
|
||||
return;
|
||||
InetAddress ia = null;
|
||||
try {
|
||||
ia = InetAddress.getByName(ips);
|
||||
} catch (UnknownHostException e) {return;}
|
||||
if (ia == null)
|
||||
return;
|
||||
byte[] ip = ia.getAddress();
|
||||
t.externalAddressReceived(Transport.SOURCE_INTERFACE, ip, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* callback from UPnP
|
||||
* Only tell SSU, it will tell NTCP
|
||||
*
|
||||
*/
|
||||
public void externalAddressReceived(String source, byte[] ip, int port) {
|
||||
Transport t = getTransport(UDPTransport.STYLE);
|
||||
if (t != null)
|
||||
t.externalAddressReceived(source, ip, port);
|
||||
}
|
||||
|
||||
/**
|
||||
* callback from UPnP
|
||||
*
|
||||
*/
|
||||
public void forwardPortStatus(String style, int port, boolean success, String reason) {
|
||||
Transport t = getTransport(style);
|
||||
if (t != null)
|
||||
t.forwardPortStatus(port, success, reason);
|
||||
}
|
||||
|
||||
public void startListening() {
|
||||
// For now, only start UPnP if we have no publicly-routable addresses
|
||||
// so we don't open the listener ports to the world.
|
||||
// Maybe we need a config option to force on? Probably not.
|
||||
// What firewall supports UPnP and is configured with a public address on the LAN side?
|
||||
// Unlikely.
|
||||
if (_upnpManager != null && Addresses.getAnyAddress() == null)
|
||||
_upnpManager.start();
|
||||
configTransports();
|
||||
_log.debug("Starting up the transport manager");
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
Transport t = (Transport)_transports.get(i);
|
||||
RouterAddress addr = t.startListening();
|
||||
_log.debug("Transport " + i + " (" + t.getStyle() + ") started");
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("Transport " + i + " (" + t.getStyle() + ") started");
|
||||
}
|
||||
// kick UPnP - Do this to get the ports opened even before UDP registers an address
|
||||
transportAddressChanged();
|
||||
_log.debug("Done start listening on transports");
|
||||
_context.router().rebuildRouterInfo();
|
||||
}
|
||||
@ -109,16 +159,18 @@ public class TransportManager implements TransportEventListener {
|
||||
}
|
||||
|
||||
public void stopListening() {
|
||||
if (_upnpManager != null)
|
||||
_upnpManager.stop();
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
((Transport)_transports.get(i)).stopListening();
|
||||
}
|
||||
_transports.clear();
|
||||
}
|
||||
|
||||
public Transport getNTCPTransport() {
|
||||
public Transport getTransport(String style) {
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
Transport t = (Transport)_transports.get(i);
|
||||
if("NTCP".equals(t.getStyle()))
|
||||
if(style.equals(t.getStyle()))
|
||||
return t;
|
||||
}
|
||||
return null;
|
||||
@ -181,15 +233,15 @@ public class TransportManager implements TransportEventListener {
|
||||
return skews;
|
||||
}
|
||||
|
||||
/** @return the best status of any transport */
|
||||
public short getReachabilityStatus() {
|
||||
if (_transports.size() <= 0) return CommSystemFacade.STATUS_UNKNOWN;
|
||||
short status[] = new short[_transports.size()];
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
status[i] = ((Transport)_transports.get(i)).getReachabilityStatus();
|
||||
short rv = CommSystemFacade.STATUS_UNKNOWN;
|
||||
for (Transport t : _transports) {
|
||||
short s = t.getReachabilityStatus();
|
||||
if (s < rv)
|
||||
rv = s;
|
||||
}
|
||||
// the values for the statuses are increasing for their 'badness'
|
||||
Arrays.sort(status);
|
||||
return status[0];
|
||||
return rv;
|
||||
}
|
||||
|
||||
public void recheckReachability() {
|
||||
@ -242,16 +294,47 @@ public class TransportManager implements TransportEventListener {
|
||||
return TransportImpl.getIP(dest);
|
||||
}
|
||||
|
||||
Map getAddresses() {
|
||||
Map rv = new HashMap(_transports.size());
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
Transport t = (Transport)_transports.get(i);
|
||||
public Map<String, RouterAddress> getAddresses() {
|
||||
Map<String, RouterAddress> rv = new HashMap(_transports.size());
|
||||
for (Transport t : _transports) {
|
||||
if (t.getCurrentAddress() != null)
|
||||
rv.put(t.getStyle(), t.getCurrentAddress());
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include the published port, or the requested port, for each transport
|
||||
* which we will pass along to UPnP
|
||||
*/
|
||||
private Map<String, Integer> getPorts() {
|
||||
Map<String, Integer> rv = new HashMap(_transports.size());
|
||||
for (Transport t : _transports) {
|
||||
int port = t.getRequestedPort();
|
||||
if (t.getCurrentAddress() != null) {
|
||||
Properties opts = t.getCurrentAddress().getOptions();
|
||||
if (opts != null) {
|
||||
String s = opts.getProperty("port");
|
||||
if (s != null) {
|
||||
try {
|
||||
port = Integer.parseInt(s);
|
||||
} catch (NumberFormatException nfe) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Use UDP port for NTCP too - see comment in NTCPTransport.getRequestedPort() for why this is here
|
||||
if (t.getStyle().equals(NTCPTransport.STYLE) && port <= 0 &&
|
||||
Boolean.valueOf(_context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT)).booleanValue()) {
|
||||
Transport udp = getTransport(UDPTransport.STYLE);
|
||||
if (udp != null)
|
||||
port = t.getRequestedPort();
|
||||
}
|
||||
if (port > 0)
|
||||
rv.put(t.getStyle(), Integer.valueOf(port));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public TransportBid getBid(OutNetMessage msg) {
|
||||
List bids = getBids(msg);
|
||||
if ( (bids == null) || (bids.size() <= 0) )
|
||||
@ -354,6 +437,11 @@ public class TransportManager implements TransportEventListener {
|
||||
}
|
||||
}
|
||||
|
||||
public void transportAddressChanged() {
|
||||
if (_upnpManager != null)
|
||||
_upnpManager.update(getPorts());
|
||||
}
|
||||
|
||||
public List getMostRecentErrorMessages() {
|
||||
List rv = new ArrayList(16);
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
@ -374,7 +462,7 @@ public class TransportManager implements TransportEventListener {
|
||||
t.renderStatusHTML(out, urlBase, sortFlags);
|
||||
}
|
||||
StringBuffer buf = new StringBuffer(4*1024);
|
||||
buf.append("Listening on: <br /><pre>\n");
|
||||
buf.append("<p><b>Router Transport Addresses:</b><br /><pre>\n");
|
||||
for (int i = 0; i < _transports.size(); i++) {
|
||||
Transport t = (Transport)_transports.get(i);
|
||||
if (t.getCurrentAddress() != null)
|
||||
@ -384,6 +472,9 @@ public class TransportManager implements TransportEventListener {
|
||||
}
|
||||
buf.append("</pre>\n");
|
||||
out.write(buf.toString());
|
||||
if (_upnpManager != null)
|
||||
out.write(_upnpManager.renderStatusHTML());
|
||||
buf.append("</p>\n");
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
690
router/java/src/net/i2p/router/transport/UPnP.java
Normal file
690
router/java/src/net/i2p/router/transport/UPnP.java
Normal file
@ -0,0 +1,690 @@
|
||||
/* This code is part of Freenet. It is distributed under the GNU General
|
||||
* Public License, version 2 (or at your option any later version). See
|
||||
* http://www.gnu.org/ for further details of the GPL. */
|
||||
package net.i2p.router.transport;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import net.i2p.util.Log;
|
||||
import net.i2p.I2PAppContext;
|
||||
|
||||
import org.cybergarage.upnp.Action;
|
||||
import org.cybergarage.upnp.ActionList;
|
||||
import org.cybergarage.upnp.Argument;
|
||||
import org.cybergarage.upnp.ArgumentList;
|
||||
import org.cybergarage.upnp.ControlPoint;
|
||||
import org.cybergarage.upnp.Device;
|
||||
import org.cybergarage.upnp.DeviceList;
|
||||
import org.cybergarage.upnp.Service;
|
||||
import org.cybergarage.upnp.ServiceList;
|
||||
import org.cybergarage.upnp.ServiceStateTable;
|
||||
import org.cybergarage.upnp.StateVariable;
|
||||
import org.cybergarage.upnp.device.DeviceChangeListener;
|
||||
import org.cybergarage.upnp.event.EventListener;
|
||||
import org.freenetproject.DetectedIP;
|
||||
import org.freenetproject.ForwardPort;
|
||||
import org.freenetproject.ForwardPortCallback;
|
||||
import org.freenetproject.ForwardPortStatus;
|
||||
|
||||
/**
|
||||
* This (and all in org/freenet, org/cybergarage, org/xmlpull)
|
||||
* grabbed from freenet SVN, mid-February 2009 by zzz.
|
||||
* This file modded somewhat to remove freenet-specific stuff,
|
||||
* but most of the glue to I2P is in UPnPManager (which was written
|
||||
* from scratch and is not the Limewire one referred to below).
|
||||
*
|
||||
* ==================
|
||||
*
|
||||
* This plugin implements UP&P support on a Freenet node.
|
||||
*
|
||||
* @author Florent Daignière <nextgens@freenetproject.org>
|
||||
*
|
||||
*
|
||||
* some code has been borrowed from Limewire : @see com.limegroup.gnutella.UPnPManager
|
||||
*
|
||||
* @see http://www.upnp.org/
|
||||
* @see http://en.wikipedia.org/wiki/Universal_Plug_and_Play
|
||||
*
|
||||
* TODO: Support multiple IGDs ?
|
||||
* TODO: Advertise the node like the MDNS plugin does
|
||||
* TODO: Implement EventListener and react on ip-change
|
||||
*/
|
||||
public class UPnP extends ControlPoint implements DeviceChangeListener, EventListener {
|
||||
private Log _log;
|
||||
private I2PAppContext _context;
|
||||
|
||||
/** some schemas */
|
||||
private static final String ROUTER_DEVICE = "urn:schemas-upnp-org:device:InternetGatewayDevice:1";
|
||||
private static final String WAN_DEVICE = "urn:schemas-upnp-org:device:WANDevice:1";
|
||||
private static final String WANCON_DEVICE = "urn:schemas-upnp-org:device:WANConnectionDevice:1";
|
||||
private static final String WAN_IP_CONNECTION = "urn:schemas-upnp-org:service:WANIPConnection:1";
|
||||
private static final String WAN_PPP_CONNECTION = "urn:schemas-upnp-org:service:WANPPPConnection:1";
|
||||
|
||||
private Device _router;
|
||||
private Service _service;
|
||||
private boolean isDisabled = false; // We disable the plugin if more than one IGD is found
|
||||
private final Object lock = new Object();
|
||||
// FIXME: detect it for real and deal with it! @see #2524
|
||||
private volatile boolean thinksWeAreDoubleNatted = false;
|
||||
|
||||
/** List of ports we want to forward */
|
||||
private Set<ForwardPort> portsToForward;
|
||||
/** List of ports we have actually forwarded */
|
||||
private Set<ForwardPort> portsForwarded;
|
||||
/** Callback to call when a forward fails or succeeds */
|
||||
private ForwardPortCallback forwardCallback;
|
||||
|
||||
public UPnP(I2PAppContext context) {
|
||||
super();
|
||||
_context = context;
|
||||
_log = _context.logManager().getLog(UPnP.class);
|
||||
portsForwarded = new HashSet<ForwardPort>();
|
||||
addDeviceChangeListener(this);
|
||||
}
|
||||
|
||||
public boolean runPlugin() {
|
||||
return super.start();
|
||||
}
|
||||
|
||||
public void terminate() {
|
||||
unregisterPortMappings();
|
||||
super.stop();
|
||||
_router = null;
|
||||
_service = null;
|
||||
}
|
||||
|
||||
public DetectedIP[] getAddress() {
|
||||
_log.info("UP&P.getAddress() is called \\o/");
|
||||
if(isDisabled) {
|
||||
_log.warn("Plugin has been disabled previously, ignoring request.");
|
||||
return null;
|
||||
} else if(!isNATPresent()) {
|
||||
_log.warn("No UP&P device found, detection of the external ip address using the plugin has failed");
|
||||
return null;
|
||||
}
|
||||
|
||||
DetectedIP result = null;
|
||||
final String natAddress = getNATAddress();
|
||||
if (natAddress == null || natAddress.length() <= 0) {
|
||||
_log.warn("No external address returned");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
InetAddress detectedIP = InetAddress.getByName(natAddress);
|
||||
|
||||
short status = DetectedIP.NOT_SUPPORTED;
|
||||
thinksWeAreDoubleNatted = !TransportImpl.isPubliclyRoutable(detectedIP.getAddress());
|
||||
// If we have forwarded a port AND we don't have a private address
|
||||
_log.warn("NATAddress: \"" + natAddress + "\" detectedIP: " + detectedIP + " double? " + thinksWeAreDoubleNatted);
|
||||
if((portsForwarded.size() > 1) && (!thinksWeAreDoubleNatted))
|
||||
status = DetectedIP.FULL_INTERNET;
|
||||
|
||||
result = new DetectedIP(detectedIP, status);
|
||||
|
||||
_log.warn("Successful UP&P discovery :" + result);
|
||||
|
||||
return new DetectedIP[] { result };
|
||||
} catch (UnknownHostException e) {
|
||||
_log.error("Caught an UnknownHostException resolving " + natAddress, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void deviceAdded(Device dev) {
|
||||
synchronized (lock) {
|
||||
if(isDisabled) {
|
||||
_log.warn("Plugin has been disabled previously, ignoring new device.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(!ROUTER_DEVICE.equals(dev.getDeviceType()) || !dev.isRootDevice()) {
|
||||
_log.warn("UP&P non-IGD device found, ignoring : " + dev.getFriendlyName());
|
||||
return; // ignore non-IGD devices
|
||||
} else if(isNATPresent()) {
|
||||
// maybe we should see if the old one went away before ignoring the new one?
|
||||
_log.warn("UP&P ignoring additional IGD device found: " + dev.getFriendlyName() + " UDN: " + dev.getUDN());
|
||||
/********** seems a little drastic
|
||||
isDisabled = true;
|
||||
|
||||
synchronized(lock) {
|
||||
_router = null;
|
||||
_service = null;
|
||||
}
|
||||
|
||||
stop();
|
||||
**************/
|
||||
return;
|
||||
}
|
||||
|
||||
_log.warn("UP&P IGD found : " + dev.getFriendlyName() + " UDN: " + dev.getUDN() + " lease time: " + dev.getLeaseTime());
|
||||
synchronized(lock) {
|
||||
_router = dev;
|
||||
}
|
||||
|
||||
discoverService();
|
||||
// We have found the device we need: stop the listener thread
|
||||
/// No, let's stick around to get notifications
|
||||
//stop();
|
||||
synchronized(lock) {
|
||||
/// we should look for the next one
|
||||
if(_service == null) {
|
||||
_log.error("The IGD device we got isn't suiting our needs, let's disable the plugin");
|
||||
isDisabled = true;
|
||||
_router = null;
|
||||
return;
|
||||
}
|
||||
subscribe(_service);
|
||||
}
|
||||
registerPortMappings();
|
||||
}
|
||||
|
||||
private void registerPortMappings() {
|
||||
Set ports;
|
||||
synchronized(lock) {
|
||||
ports = portsToForward;
|
||||
}
|
||||
if(ports == null) return;
|
||||
registerPorts(ports);
|
||||
}
|
||||
|
||||
/**
|
||||
* Traverses the structure of the router device looking for the port mapping service.
|
||||
*/
|
||||
private void discoverService() {
|
||||
synchronized (lock) {
|
||||
for (Iterator iter = _router.getDeviceList().iterator();iter.hasNext();) {
|
||||
Device current = (Device)iter.next();
|
||||
if (!current.getDeviceType().equals(WAN_DEVICE))
|
||||
continue;
|
||||
|
||||
DeviceList l = current.getDeviceList();
|
||||
for (int i=0;i<current.getDeviceList().size();i++) {
|
||||
Device current2 = l.getDevice(i);
|
||||
if (!current2.getDeviceType().equals(WANCON_DEVICE))
|
||||
continue;
|
||||
|
||||
_service = current2.getService(WAN_PPP_CONNECTION);
|
||||
if(_service == null) {
|
||||
_log.warn(_router.getFriendlyName()+ " doesn't seems to be using PPP; we won't be able to extract bandwidth-related informations out of it.");
|
||||
_service = current2.getService(WAN_IP_CONNECTION);
|
||||
if(_service == null)
|
||||
_log.error(_router.getFriendlyName()+ " doesn't export WAN_IP_CONNECTION either: we won't be able to use it!");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean tryAddMapping(String protocol, int port, String description, ForwardPort fp) {
|
||||
_log.warn("Registering a port mapping for " + port + "/" + protocol);
|
||||
int nbOfTries = 0;
|
||||
boolean isPortForwarded = false;
|
||||
while(nbOfTries++ < 5) {
|
||||
isPortForwarded = addMapping(protocol, port, "I2P " + description, fp);
|
||||
if(isPortForwarded)
|
||||
break;
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {}
|
||||
}
|
||||
_log.warn((isPortForwarded ? "Mapping is successful!" : "Mapping has failed!") + " ("+ nbOfTries + " tries)");
|
||||
return isPortForwarded;
|
||||
}
|
||||
|
||||
public void unregisterPortMappings() {
|
||||
Set ports;
|
||||
synchronized(lock) {
|
||||
ports = new HashSet(portsForwarded);
|
||||
}
|
||||
this.unregisterPorts(ports);
|
||||
}
|
||||
|
||||
public void deviceRemoved(Device dev ){
|
||||
_log.warn("UP&P device removed : " + dev.getFriendlyName() + " UDN: " + dev.getUDN());
|
||||
synchronized (lock) {
|
||||
if(_router == null) return;
|
||||
// I2P this wasn't working
|
||||
//if(_router.equals(dev)) {
|
||||
if(ROUTER_DEVICE.equals(dev.getDeviceType()) &&
|
||||
dev.isRootDevice() &&
|
||||
stringEquals(_router.getFriendlyName(), dev.getFriendlyName()) &&
|
||||
stringEquals(_router.getUDN(), dev.getUDN())) {
|
||||
_log.warn("UP&P IGD device removed : " + dev.getFriendlyName());
|
||||
_router = null;
|
||||
_service = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** event callback */
|
||||
public void eventNotifyReceived(String uuid, long seq, String varName, String value) {
|
||||
_log.error("Event: " + uuid + ' ' + seq + ' ' + varName + '=' + value);
|
||||
}
|
||||
|
||||
/** compare two strings, either of which could be null */
|
||||
private static boolean stringEquals(String a, String b) {
|
||||
if (a != null)
|
||||
return a.equals(b);
|
||||
return b == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether we are behind an UPnP-enabled NAT/router
|
||||
*/
|
||||
public boolean isNATPresent() {
|
||||
return _router != null && _service != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the external address the NAT thinks we have. Blocking.
|
||||
* null if we can't find it.
|
||||
*/
|
||||
public String getNATAddress() {
|
||||
if(!isNATPresent())
|
||||
return null;
|
||||
|
||||
Action getIP = _service.getAction("GetExternalIPAddress");
|
||||
if(getIP == null || !getIP.postControlAction())
|
||||
return null;
|
||||
|
||||
String rv = (getIP.getOutputArgumentList().getArgument("NewExternalIPAddress")).getValue();
|
||||
// I2P some devices return 0.0.0.0 when not connected
|
||||
if ("0.0.0.0".equals(rv))
|
||||
return null;
|
||||
return rv;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the reported upstream bit rate in bits per second. -1 if it's not available. Blocking.
|
||||
*/
|
||||
public int getUpstramMaxBitRate() {
|
||||
if(!isNATPresent() || thinksWeAreDoubleNatted)
|
||||
return -1;
|
||||
|
||||
Action getIP = _service.getAction("GetLinkLayerMaxBitRates");
|
||||
if(getIP == null || !getIP.postControlAction())
|
||||
return -1;
|
||||
|
||||
return Integer.valueOf(getIP.getOutputArgumentList().getArgument("NewUpstreamMaxBitRate").getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the reported downstream bit rate in bits per second. -1 if it's not available. Blocking.
|
||||
*/
|
||||
public int getDownstreamMaxBitRate() {
|
||||
if(!isNATPresent() || thinksWeAreDoubleNatted)
|
||||
return -1;
|
||||
|
||||
Action getIP = _service.getAction("GetLinkLayerMaxBitRates");
|
||||
if(getIP == null || !getIP.postControlAction())
|
||||
return -1;
|
||||
|
||||
return Integer.valueOf(getIP.getOutputArgumentList().getArgument("NewDownstreamMaxBitRate").getValue());
|
||||
}
|
||||
|
||||
/***
|
||||
private void listStateTable(Service serv, StringBuilder sb) {
|
||||
ServiceStateTable table = serv.getServiceStateTable();
|
||||
sb.append("<div><small>");
|
||||
for(int i=0; i<table.size(); i++) {
|
||||
StateVariable current = table.getStateVariable(i);
|
||||
sb.append(current.getName() + " : " + current.getValue() + "<br>");
|
||||
}
|
||||
sb.append("</small></div>");
|
||||
}
|
||||
|
||||
private void listActionsArguments(Action action, StringBuilder sb) {
|
||||
ArgumentList ar = action.getArgumentList();
|
||||
for(int i=0; i<ar.size(); i++) {
|
||||
Argument argument = ar.getArgument(i);
|
||||
if(argument == null ) continue;
|
||||
sb.append("<div><small>argument ("+i+") :" + argument.getName()+"</small></div>");
|
||||
}
|
||||
}
|
||||
|
||||
private void listActions(Service service, StringBuilder sb) {
|
||||
ActionList al = service.getActionList();
|
||||
for(int i=0; i<al.size(); i++) {
|
||||
Action action = al.getAction(i);
|
||||
if(action == null ) continue;
|
||||
sb.append("<div>action ("+i+") :" + action.getName());
|
||||
listActionsArguments(action, sb);
|
||||
sb.append("</div>");
|
||||
}
|
||||
}
|
||||
***/
|
||||
|
||||
private String toString(String action, String Argument, Service serv) {
|
||||
Action getIP = serv.getAction(action);
|
||||
if(getIP == null || !getIP.postControlAction())
|
||||
return null;
|
||||
|
||||
Argument ret = getIP.getOutputArgumentList().getArgument(Argument);
|
||||
return ret.getValue();
|
||||
}
|
||||
|
||||
// TODO: extend it! RTFM
|
||||
private void listSubServices(Device dev, StringBuilder sb) {
|
||||
ServiceList sl = dev.getServiceList();
|
||||
if (sl.size() <= 0)
|
||||
return;
|
||||
sb.append("<ul>\n");
|
||||
for(int i=0; i<sl.size(); i++) {
|
||||
Service serv = sl.getService(i);
|
||||
if(serv == null) continue;
|
||||
sb.append("<li>Service: ");
|
||||
if("urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1".equals(serv.getServiceType())){
|
||||
sb.append("WAN Common Interface Config<ul>");
|
||||
sb.append("<li>Status: " + toString("GetCommonLinkProperties", "NewPhysicalLinkStatus", serv));
|
||||
sb.append("<li>Type: " + toString("GetCommonLinkProperties", "NewWANAccessType", serv));
|
||||
sb.append("<li>Upstream: " + toString("GetCommonLinkProperties", "NewLayer1UpstreamMaxBitRate", serv));
|
||||
sb.append("<li>Downstream: " + toString("GetCommonLinkProperties", "NewLayer1DownstreamMaxBitRate", serv) + "<br>");
|
||||
}else if("urn:schemas-upnp-org:service:WANPPPConnection:1".equals(serv.getServiceType())){
|
||||
sb.append("WAN PPP Connection<ul>");
|
||||
sb.append("<li>Status: " + toString("GetStatusInfo", "NewConnectionStatus", serv));
|
||||
sb.append("<li>Type: " + toString("GetConnectionTypeInfo", "NewConnectionType", serv));
|
||||
sb.append("<li>Upstream: " + toString("GetLinkLayerMaxBitRates", "NewUpstreamMaxBitRate", serv));
|
||||
sb.append("<li>Downstream: " + toString("GetLinkLayerMaxBitRates", "NewDownstreamMaxBitRate", serv) + "<br>");
|
||||
sb.append("<li>External IP: " + toString("GetExternalIPAddress", "NewExternalIPAddress", serv) + "<br>");
|
||||
}else if("urn:schemas-upnp-org:service:Layer3Forwarding:1".equals(serv.getServiceType())){
|
||||
sb.append("Layer 3 Forwarding<ul>");
|
||||
sb.append("<li>Default Connection Service: " + toString("GetDefaultConnectionService", "NewDefaultConnectionService", serv));
|
||||
}else if(WAN_IP_CONNECTION.equals(serv.getServiceType())){
|
||||
sb.append("WAN IP Connection<ul>");
|
||||
sb.append("<li>Status: " + toString("GetStatusInfo", "NewConnectionStatus", serv));
|
||||
sb.append("<li>Type: " + toString("GetConnectionTypeInfo", "NewConnectionType", serv));
|
||||
sb.append("<li>External IP: " + toString("GetExternalIPAddress", "NewExternalIPAddress", serv) + "<br>");
|
||||
}else if("urn:schemas-upnp-org:service:WANEthernetLinkConfig:1".equals(serv.getServiceType())){
|
||||
sb.append("WAN Ethernet Link Config<ol>");
|
||||
sb.append("<li>Status: " + toString("GetEthernetLinkStatus", "NewEthernetLinkStatus", serv) + "<br>");
|
||||
}else
|
||||
sb.append("~~~~~~~ "+serv.getServiceType() + "<ul>");
|
||||
//listActions(serv, sb);
|
||||
//listStateTable(serv, sb);
|
||||
sb.append("</ul>\n");
|
||||
}
|
||||
sb.append("</ul>\n");
|
||||
}
|
||||
|
||||
private void listSubDev(String prefix, Device dev, StringBuilder sb){
|
||||
if (prefix == null)
|
||||
sb.append("Device: ");
|
||||
else
|
||||
sb.append("<li>Subdevice: ");
|
||||
sb.append(dev.getFriendlyName());
|
||||
listSubServices(dev, sb);
|
||||
|
||||
DeviceList dl = dev.getDeviceList();
|
||||
if (dl.size() <= 0)
|
||||
return;
|
||||
sb.append("<ul>\n");
|
||||
for(int j=0; j<dl.size(); j++) {
|
||||
Device subDev = dl.getDevice(j);
|
||||
if(subDev == null) continue;
|
||||
listSubDev(dev.getFriendlyName(), subDev, sb);
|
||||
}
|
||||
sb.append("</ul>\n");
|
||||
}
|
||||
|
||||
public String renderStatusHTML() {
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
sb.append("<a name=\"upnp\"><b>UPnP Status:</b><br />");
|
||||
|
||||
if(isDisabled) {
|
||||
sb.append("UPnP has been disabled; Do you have more than one UPnP Internet Gateway Device on your LAN ?");
|
||||
return sb.toString();
|
||||
} else if(!isNATPresent()) {
|
||||
sb.append("UPnP has not found any UPnP-aware, compatible device on your LAN.");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// FIXME L10n!
|
||||
sb.append("<p>Found ");
|
||||
listSubDev(null, _router, sb);
|
||||
String addr = getNATAddress();
|
||||
if (addr != null)
|
||||
sb.append("<br>The current external IP address reported by UPnP is " + addr);
|
||||
else
|
||||
sb.append("<br>The current external IP address is not available.");
|
||||
int downstreamMaxBitRate = getDownstreamMaxBitRate();
|
||||
int upstreamMaxBitRate = getUpstramMaxBitRate();
|
||||
if(downstreamMaxBitRate > 0)
|
||||
sb.append("<br>UPnP reports the max downstream bit rate is : " + getDownstreamMaxBitRate()+ " bits/sec\n");
|
||||
if(upstreamMaxBitRate > 0)
|
||||
sb.append("<br>UPnP reports the max upstream bit rate is : " + getUpstramMaxBitRate()+ " bits/sec\n");
|
||||
synchronized(lock) {
|
||||
if(portsToForward != null) {
|
||||
for(ForwardPort port : portsToForward) {
|
||||
sb.append("<br>" + protoToString(port.protocol) + " port " + port.portNumber + " for " + port.name);
|
||||
if(portsForwarded.contains(port))
|
||||
sb.append(" has been forwarded successfully by UPnP.\n");
|
||||
else
|
||||
sb.append(" has not been forwarded by UPnP.\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("</p>");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private boolean addMapping(String protocol, int port, String description, ForwardPort fp) {
|
||||
if(isDisabled || !isNATPresent() || _router == null) {
|
||||
_log.error("Can't addMapping: " + isDisabled + " " + isNATPresent() + " " + _router);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Just in case...
|
||||
// this confuses my linksys? - zzz
|
||||
removeMapping(protocol, port, fp, true);
|
||||
|
||||
Action add = _service.getAction("AddPortMapping");
|
||||
if(add == null) {
|
||||
_log.error("Couldn't find AddPortMapping action!");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
add.setArgumentValue("NewRemoteHost", "");
|
||||
add.setArgumentValue("NewExternalPort", port);
|
||||
add.setArgumentValue("NewInternalClient", _router.getInterfaceAddress());
|
||||
add.setArgumentValue("NewInternalPort", port);
|
||||
add.setArgumentValue("NewProtocol", protocol);
|
||||
add.setArgumentValue("NewPortMappingDescription", description);
|
||||
add.setArgumentValue("NewEnabled","1");
|
||||
add.setArgumentValue("NewLeaseDuration", 0);
|
||||
|
||||
if(add.postControlAction()) {
|
||||
synchronized(lock) {
|
||||
portsForwarded.add(fp);
|
||||
}
|
||||
return true;
|
||||
} else return false;
|
||||
}
|
||||
|
||||
private boolean removeMapping(String protocol, int port, ForwardPort fp, boolean noLog) {
|
||||
if(isDisabled || !isNATPresent())
|
||||
return false;
|
||||
|
||||
Action remove = _service.getAction("DeletePortMapping");
|
||||
if(remove == null) {
|
||||
_log.error("Couldn't find DeletePortMapping action!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// remove.setArgumentValue("NewRemoteHost", "");
|
||||
remove.setArgumentValue("NewExternalPort", port);
|
||||
remove.setArgumentValue("NewProtocol", protocol);
|
||||
|
||||
boolean retval = remove.postControlAction();
|
||||
synchronized(lock) {
|
||||
portsForwarded.remove(fp);
|
||||
}
|
||||
|
||||
if(!noLog)
|
||||
_log.warn("UPnP: Removed mapping for "+fp.name+" "+port+" / "+protocol);
|
||||
return retval;
|
||||
}
|
||||
|
||||
public void onChangePublicPorts(Set<ForwardPort> ports, ForwardPortCallback cb) {
|
||||
Set<ForwardPort> portsToDumpNow = null;
|
||||
Set<ForwardPort> portsToForwardNow = null;
|
||||
_log.warn("UP&P Forwarding "+ports.size()+" ports...");
|
||||
synchronized(lock) {
|
||||
if(forwardCallback != null && forwardCallback != cb && cb != null) {
|
||||
_log.error("ForwardPortCallback changed from "+forwardCallback+" to "+cb+" - using new value, but this is very strange!");
|
||||
}
|
||||
forwardCallback = cb;
|
||||
if(portsToForward == null || portsToForward.isEmpty()) {
|
||||
portsToForward = ports;
|
||||
portsToForwardNow = ports;
|
||||
portsToDumpNow = null;
|
||||
} else if(ports == null || ports.isEmpty()) {
|
||||
portsToDumpNow = portsToForward;
|
||||
portsToForward = ports;
|
||||
portsToForwardNow = null;
|
||||
} else {
|
||||
// Some ports to keep, some ports to dump
|
||||
// Ports in ports but not in portsToForwardNow we must forward
|
||||
// Ports in portsToForwardNow but not in ports we must dump
|
||||
for(ForwardPort port: ports) {
|
||||
if(portsToForward.contains(port)) {
|
||||
// We have forwarded it, and it should be forwarded, cool.
|
||||
} else {
|
||||
// Needs forwarding
|
||||
if(portsToForwardNow == null) portsToForwardNow = new HashSet<ForwardPort>();
|
||||
portsToForwardNow.add(port);
|
||||
}
|
||||
}
|
||||
for(ForwardPort port : portsToForward) {
|
||||
if(ports.contains(port)) {
|
||||
// Should be forwarded, has been forwarded, cool.
|
||||
} else {
|
||||
// Needs dropping
|
||||
if(portsToDumpNow == null) portsToDumpNow = new HashSet<ForwardPort>();
|
||||
portsToDumpNow.add(port);
|
||||
}
|
||||
}
|
||||
portsToForward = ports;
|
||||
}
|
||||
if(_router == null) return; // When one is found, we will do the forwards
|
||||
}
|
||||
if(portsToDumpNow != null)
|
||||
unregisterPorts(portsToDumpNow);
|
||||
if(portsToForwardNow != null)
|
||||
registerPorts(portsToForwardNow);
|
||||
}
|
||||
|
||||
private static String protoToString(int p) {
|
||||
if(p == ForwardPort.PROTOCOL_UDP_IPV4)
|
||||
return "UDP";
|
||||
if(p == ForwardPort.PROTOCOL_TCP_IPV4)
|
||||
return "TCP";
|
||||
return "?";
|
||||
}
|
||||
|
||||
private static int __id = 0;
|
||||
|
||||
/**
|
||||
* postControlAction() can take many seconds, especially if it's failing,
|
||||
* and onChangePublicPorts() may be called from threads we don't want to slow down,
|
||||
* so throw this in a thread.
|
||||
*/
|
||||
private void registerPorts(Set<ForwardPort> portsToForwardNow) {
|
||||
Thread t = new Thread(new RegisterPortsThread(portsToForwardNow));
|
||||
t.setName("UPnP Port Opener " + (++__id));
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
}
|
||||
|
||||
private class RegisterPortsThread implements Runnable {
|
||||
private Set<ForwardPort> portsToForwardNow;
|
||||
|
||||
public RegisterPortsThread(Set<ForwardPort> ports) {
|
||||
portsToForwardNow = ports;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
for(ForwardPort port : portsToForwardNow) {
|
||||
String proto = protoToString(port.protocol);
|
||||
if (proto.length() <= 1) {
|
||||
HashMap<ForwardPort, ForwardPortStatus> map = new HashMap<ForwardPort, ForwardPortStatus>();
|
||||
map.put(port, new ForwardPortStatus(ForwardPortStatus.DEFINITE_FAILURE, "Protocol not supported", port.portNumber));
|
||||
forwardCallback.portForwardStatus(map);
|
||||
continue;
|
||||
}
|
||||
if(tryAddMapping(proto, port.portNumber, port.name, port)) {
|
||||
HashMap<ForwardPort, ForwardPortStatus> map = new HashMap<ForwardPort, ForwardPortStatus>();
|
||||
map.put(port, new ForwardPortStatus(ForwardPortStatus.MAYBE_SUCCESS, "Port apparently forwarded by UPnP", port.portNumber));
|
||||
forwardCallback.portForwardStatus(map);
|
||||
continue;
|
||||
} else {
|
||||
HashMap<ForwardPort, ForwardPortStatus> map = new HashMap<ForwardPort, ForwardPortStatus>();
|
||||
map.put(port, new ForwardPortStatus(ForwardPortStatus.PROBABLE_FAILURE, "UPnP port forwarding apparently failed", port.portNumber));
|
||||
forwardCallback.portForwardStatus(map);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* postControlAction() can take many seconds, especially if it's failing,
|
||||
* and onChangePublicPorts() may be called from threads we don't want to slow down,
|
||||
* so throw this in a thread.
|
||||
*/
|
||||
private void unregisterPorts(Set<ForwardPort> portsToForwardNow) {
|
||||
Thread t = new Thread(new UnregisterPortsThread(portsToForwardNow));
|
||||
t.setName("UPnP Port Opener " + (++__id));
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
}
|
||||
|
||||
private class UnregisterPortsThread implements Runnable {
|
||||
private Set<ForwardPort> portsToForwardNow;
|
||||
|
||||
public UnregisterPortsThread(Set<ForwardPort> ports) {
|
||||
portsToForwardNow = ports;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
for(ForwardPort port : portsToForwardNow) {
|
||||
String proto = protoToString(port.protocol);
|
||||
if (proto.length() <= 1)
|
||||
// Ignore, we've already complained about it
|
||||
continue;
|
||||
removeMapping(proto, port.portNumber, port, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
UPnP upnp = new UPnP(I2PAppContext.getGlobalContext());
|
||||
ControlPoint cp = new ControlPoint();
|
||||
System.out.println("Searching for up&p devices:");
|
||||
cp.start();
|
||||
cp.search();
|
||||
while(true) {
|
||||
DeviceList list = cp.getDeviceList();
|
||||
System.out.println("Found " + list.size() + " devices!");
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Iterator<Device> it = list.iterator();
|
||||
while(it.hasNext()) {
|
||||
Device device = it.next();
|
||||
upnp.listSubDev(device.toString(), device, sb);
|
||||
System.out.println("Here is the listing for " + device.toString() + " :");
|
||||
System.out.println(sb.toString());
|
||||
sb = new StringBuilder();
|
||||
}
|
||||
System.out.println("End");
|
||||
Thread.sleep(2000);
|
||||
}
|
||||
}
|
||||
}
|
156
router/java/src/net/i2p/router/transport/UPnPManager.java
Normal file
156
router/java/src/net/i2p/router/transport/UPnPManager.java
Normal file
@ -0,0 +1,156 @@
|
||||
package net.i2p.router.transport;
|
||||
|
||||
/*
|
||||
* public domain
|
||||
*/
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import net.i2p.data.RouterAddress;
|
||||
import net.i2p.router.RouterContext;
|
||||
import net.i2p.util.Log;
|
||||
|
||||
import org.cybergarage.util.Debug;
|
||||
import org.freenetproject.DetectedIP;
|
||||
import org.freenetproject.ForwardPort;
|
||||
import org.freenetproject.ForwardPortCallback;
|
||||
import org.freenetproject.ForwardPortStatus;
|
||||
|
||||
/**
|
||||
* Bridge from the I2P RouterAddress data structure to
|
||||
* the freenet data structures
|
||||
*
|
||||
* @author zzz
|
||||
*/
|
||||
public class UPnPManager {
|
||||
private Log _log;
|
||||
private RouterContext _context;
|
||||
private UPnP _upnp;
|
||||
private UPnPCallback _upnpCallback;
|
||||
private boolean _isRunning;
|
||||
private InetAddress _detectedAddress;
|
||||
private TransportManager _manager;
|
||||
/**
|
||||
* This is the TCP HTTP Event listener
|
||||
* We move these so we don't conflict with other users of the same upnp library
|
||||
* UPnP also binds to port 1900 UDP for multicast reception - this cannot be changed.
|
||||
*/
|
||||
private static final String PROP_HTTP_PORT = "i2np.upnp.HTTPPort";
|
||||
private static final int DEFAULT_HTTP_PORT = 7652;
|
||||
/** this is the UDP SSDP Search reply listener */
|
||||
private static final String PROP_SSDP_PORT = "i2np.upnp.SSDPPort";
|
||||
private static final int DEFAULT_SSDP_PORT = 7653;
|
||||
|
||||
public UPnPManager(RouterContext context, TransportManager manager) {
|
||||
_context = context;
|
||||
_manager = manager;
|
||||
_log = _context.logManager().getLog(UPnPManager.class);
|
||||
_upnp = new UPnP(context);
|
||||
_upnp.setHTTPPort(_context.getProperty(PROP_HTTP_PORT, DEFAULT_HTTP_PORT));
|
||||
_upnp.setSSDPPort(_context.getProperty(PROP_SSDP_PORT, DEFAULT_SSDP_PORT));
|
||||
_upnpCallback = new UPnPCallback();
|
||||
_isRunning = false;
|
||||
}
|
||||
|
||||
public synchronized void start() {
|
||||
if (_log.shouldLog(Log.DEBUG)) {
|
||||
_log.debug("UPnP Start");
|
||||
Debug.on(); // UPnP stuff -> wrapper log
|
||||
}
|
||||
if (!_isRunning)
|
||||
_isRunning = _upnp.runPlugin();
|
||||
if (!_isRunning)
|
||||
_log.error("UPnP start failed - port conflict?");
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("UPnP Stop");
|
||||
if (_isRunning)
|
||||
_upnp.terminate();
|
||||
_isRunning = false;
|
||||
_detectedAddress = null;
|
||||
}
|
||||
|
||||
/** call when the ports might have changed */
|
||||
public void update(Map<String, Integer> ports) {
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("UPnP Update:");
|
||||
if (!_isRunning)
|
||||
return;
|
||||
Set<ForwardPort> forwards = new HashSet(ports.size());
|
||||
for (String style : ports.keySet()) {
|
||||
int port = ports.get(style).intValue();
|
||||
int protocol = -1;
|
||||
if ("SSU".equals(style))
|
||||
protocol = ForwardPort.PROTOCOL_UDP_IPV4;
|
||||
else if ("NTCP".equals(style))
|
||||
protocol = ForwardPort.PROTOCOL_TCP_IPV4;
|
||||
else
|
||||
continue;
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("Adding: " + style + " " + port);
|
||||
ForwardPort fp = new ForwardPort(style, false, protocol, port);
|
||||
forwards.add(fp);
|
||||
}
|
||||
_upnp.onChangePublicPorts(forwards, _upnpCallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the callback from UPnP.
|
||||
* It calls the TransportManager callbacks.
|
||||
*/
|
||||
private class UPnPCallback implements ForwardPortCallback {
|
||||
|
||||
/** Called to indicate status on one or more forwarded ports. */
|
||||
public void portForwardStatus(Map<ForwardPort,ForwardPortStatus> statuses) {
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("UPnP Callback:");
|
||||
|
||||
DetectedIP[] ips = _upnp.getAddress();
|
||||
byte[] detected = null;
|
||||
if (ips != null) {
|
||||
for (DetectedIP ip : ips) {
|
||||
// store the first public one and tell the transport manager if it changed
|
||||
if (TransportImpl.isPubliclyRoutable(ip.publicAddress.getAddress())) {
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("External address: " + ip.publicAddress + " type: " + ip.natType);
|
||||
if (!ip.publicAddress.equals(_detectedAddress)) {
|
||||
_detectedAddress = ip.publicAddress;
|
||||
_manager.externalAddressReceived(Transport.SOURCE_UPNP, _detectedAddress.getAddress(), 0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("No external address returned");
|
||||
}
|
||||
|
||||
for (ForwardPort fp : statuses.keySet()) {
|
||||
ForwardPortStatus fps = statuses.get(fp);
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug(fp.name + " " + fp.protocol + " " + fp.portNumber +
|
||||
" status: " + fps.status + " reason: " + fps.reasonString + " ext port: " + fps.externalPort);
|
||||
String style;
|
||||
if (fp.protocol == ForwardPort.PROTOCOL_UDP_IPV4)
|
||||
style = "SSU";
|
||||
else if (fp.protocol == ForwardPort.PROTOCOL_TCP_IPV4)
|
||||
style = "NTCP";
|
||||
else
|
||||
continue;
|
||||
boolean success = fps.status >= ForwardPortStatus.MAYBE_SUCCESS;
|
||||
_manager.forwardPortStatus(style, fp.portNumber, success, fps.reasonString);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String renderStatusHTML() {
|
||||
if (!_isRunning)
|
||||
return "<a name=\"upnp\"><<b>UPnP is not enabled</b>\n";
|
||||
return _upnp.renderStatusHTML();
|
||||
}
|
||||
}
|
@ -20,6 +20,7 @@ import net.i2p.data.Hash;
|
||||
import net.i2p.data.RouterAddress;
|
||||
import net.i2p.data.RouterIdentity;
|
||||
import net.i2p.data.RouterInfo;
|
||||
import net.i2p.router.CommSystemFacade;
|
||||
import net.i2p.router.OutNetMessage;
|
||||
import net.i2p.router.RouterContext;
|
||||
import net.i2p.router.transport.CommSystemFacadeImpl;
|
||||
@ -37,7 +38,7 @@ public class NTCPTransport extends TransportImpl {
|
||||
private SharedBid _slowBid;
|
||||
private SharedBid _transientFail;
|
||||
private final Object _conLock;
|
||||
private Map _conByIdent;
|
||||
private Map<Hash, NTCPConnection> _conByIdent;
|
||||
private NTCPAddress _myAddress;
|
||||
private EventPumper _pumper;
|
||||
private Reader _reader;
|
||||
@ -539,6 +540,54 @@ public class NTCPTransport extends TransportImpl {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If we didn't used to be forwarded, and we have an address,
|
||||
* and we are configured to use UPnP, update our RouterAddress
|
||||
*
|
||||
* Don't do anything now. If it fails, we don't know if it's
|
||||
* because there is no firewall, or if the firewall rejected the request.
|
||||
* So we just use the SSU reachability status
|
||||
* to decide whether to enable inbound NTCP. SSU will have CSFI build a new
|
||||
* NTCP address when it transitions to OK.
|
||||
*/
|
||||
public void forwardPortStatus(int port, boolean success, String reason) {
|
||||
if (_log.shouldLog(Log.WARN)) {
|
||||
if (success)
|
||||
_log.warn("UPnP has opened the NTCP port: " + port);
|
||||
else
|
||||
_log.warn("UPnP has failed to open the NTCP port: " + port + " reason: " + reason);
|
||||
}
|
||||
}
|
||||
|
||||
public int getRequestedPort() {
|
||||
// would be nice to do this here but we can't easily get to the UDP transport.getRequested_Port()
|
||||
// from here, so we do it in TransportManager.
|
||||
// if (Boolean.valueOf(_context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT)).booleanValue())
|
||||
// return foo;
|
||||
return _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maybe we should trust UPnP here and report OK if it opened the port, but
|
||||
* for now we don't. Just go through and if we have one inbound connection,
|
||||
* we must be good. As we drop idle connections pretty quickly, this will
|
||||
* be fairly accurate.
|
||||
*
|
||||
* We have to be careful here because much of the router console code assumes
|
||||
* that the reachability status is really just the UDP status.
|
||||
*/
|
||||
public short getReachabilityStatus() {
|
||||
if (isAlive() && _myAddress != null) {
|
||||
synchronized (_conLock) {
|
||||
for (NTCPConnection con : _conByIdent.values()) {
|
||||
if (con.isInbound())
|
||||
return CommSystemFacade.STATUS_OK;
|
||||
}
|
||||
}
|
||||
}
|
||||
return CommSystemFacade.STATUS_UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* This doesn't (completely) block, caller should check isAlive()
|
||||
* before calling startListening() or restartListening()
|
||||
@ -558,6 +607,8 @@ public class NTCPTransport extends TransportImpl {
|
||||
NTCPConnection con = (NTCPConnection)iter.next();
|
||||
con.close();
|
||||
}
|
||||
// will this work?
|
||||
replaceAddress(null);
|
||||
}
|
||||
public static final String STYLE = "NTCP";
|
||||
|
||||
|
@ -30,7 +30,7 @@ public class InboundMessageState {
|
||||
|
||||
/** expire after 10s */
|
||||
private static final long MAX_RECEIVE_TIME = 10*1000;
|
||||
private static final int MAX_FRAGMENTS = 64;
|
||||
public static final int MAX_FRAGMENTS = 64;
|
||||
|
||||
private static final ByteCache _fragmentCache = ByteCache.getInstance(64, 2048);
|
||||
|
||||
|
@ -34,8 +34,11 @@ public class OutboundMessageState {
|
||||
private short _maxSends;
|
||||
private int _nextSendFragment;
|
||||
|
||||
public static final int MAX_FRAGMENTS = 32;
|
||||
private static final ByteCache _cache = ByteCache.getInstance(64, MAX_FRAGMENTS*1024);
|
||||
public static final int MAX_MSG_SIZE = 32 * 1024;
|
||||
/** is this enough for a high-bandwidth router? */
|
||||
private static final int MAX_ENTRIES = 64;
|
||||
/** would two caches, one for small and one for large messages, be better? */
|
||||
private static final ByteCache _cache = ByteCache.getInstance(MAX_ENTRIES, MAX_MSG_SIZE);
|
||||
|
||||
public OutboundMessageState(I2PAppContext context) {
|
||||
_context = context;
|
||||
@ -226,7 +229,9 @@ public class OutboundMessageState {
|
||||
int numFragments = totalSize / fragmentSize;
|
||||
if (numFragments * fragmentSize < totalSize)
|
||||
numFragments++;
|
||||
|
||||
// This should never happen, as 534 bytes * 64 fragments > 32KB, and we won't bid on > 32KB
|
||||
if (numFragments > InboundMessageState.MAX_FRAGMENTS)
|
||||
throw new IllegalArgumentException("Fragmenting a " + totalSize + " message into " + numFragments + " fragments - too many!");
|
||||
if (_log.shouldLog(Log.DEBUG))
|
||||
_log.debug("Fragmenting a " + totalSize + " message into " + numFragments + " fragments");
|
||||
|
||||
|
@ -287,15 +287,7 @@ public class PeerState {
|
||||
}
|
||||
|
||||
private int getDefaultMTU() {
|
||||
String mtu = _context.getProperty(PROP_DEFAULT_MTU);
|
||||
if (mtu != null) {
|
||||
try {
|
||||
return Integer.valueOf(mtu).intValue();
|
||||
} catch (NumberFormatException nfe) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
return DEFAULT_MTU;
|
||||
return _context.getProperty(PROP_DEFAULT_MTU, DEFAULT_MTU);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -99,6 +99,10 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
|
||||
public static final String STYLE = "SSU";
|
||||
public static final String PROP_INTERNAL_PORT = "i2np.udp.internalPort";
|
||||
public static final int DEFAULT_INTERNAL_PORT = 8887;
|
||||
/** since fixed port defaults to true, this doesnt do anything at the moment.
|
||||
* We should have an exception if it matches the existing low port. */
|
||||
private static final int MIN_EXTERNAL_PORT = 1024;
|
||||
|
||||
/** define this to explicitly set an external IP address */
|
||||
public static final String PROP_EXTERNAL_HOST = "i2np.udp.host";
|
||||
@ -117,9 +121,17 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
public static final String PROP_PREFER_UDP = "i2np.udp.preferred";
|
||||
private static final String DEFAULT_PREFER_UDP = "false";
|
||||
|
||||
/** if true (default), we don't change our advertised port no matter what our peers tell us */
|
||||
public static final String PROP_FIXED_PORT = "i2np.udp.fixedPort";
|
||||
private static final String DEFAULT_FIXED_PORT = "true";
|
||||
|
||||
/** allowed sources of address updates */
|
||||
public static final String PROP_SOURCES = "i2np.udp.addressSources";
|
||||
public static final String DEFAULT_SOURCES = "local,upnp,ssu";
|
||||
/** remember IP changes */
|
||||
public static final String PROP_IP= "i2np.lastIP";
|
||||
public static final String PROP_IP_CHANGE = "i2np.lastIPChange";
|
||||
|
||||
/** do we require introducers, regardless of our status? */
|
||||
public static final String PROP_FORCE_INTRODUCERS = "i2np.udp.forceIntroducers";
|
||||
/** do we allow direct SSU connections, sans introducers? */
|
||||
@ -215,22 +227,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
int port = -1;
|
||||
if (_externalListenPort <= 0) {
|
||||
// no explicit external port, so lets try an internal one
|
||||
String portStr = _context.getProperty(PROP_INTERNAL_PORT);
|
||||
if (portStr != null) {
|
||||
try {
|
||||
port = Integer.parseInt(portStr);
|
||||
} catch (NumberFormatException nfe) {
|
||||
if (_log.shouldLog(Log.ERROR))
|
||||
_log.error("Invalid port specified [" + portStr + "]");
|
||||
}
|
||||
}
|
||||
if (port <= 0) {
|
||||
port = 8887;
|
||||
//port = 1024 + _context.random().nextInt(31*1024);
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Selecting an arbitrary port to bind to: " + port);
|
||||
_context.router().setConfigSetting(PROP_INTERNAL_PORT, port+"");
|
||||
}
|
||||
port = _context.getProperty(PROP_INTERNAL_PORT, DEFAULT_INTERNAL_PORT);
|
||||
// attempt to use it as our external port - this will be overridden by
|
||||
// externalAddressReceived(...)
|
||||
_context.router().setConfigSetting(PROP_EXTERNAL_PORT, port+"");
|
||||
@ -321,7 +318,12 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
public int getLocalPort() { return _externalListenPort; }
|
||||
public InetAddress getLocalAddress() { return _externalListenHost; }
|
||||
public int getExternalPort() { return _externalListenPort; }
|
||||
|
||||
public int getRequestedPort() {
|
||||
if (_externalListenPort > 0)
|
||||
return _externalListenPort;
|
||||
return _context.getProperty(PROP_INTERNAL_PORT, DEFAULT_INTERNAL_PORT);
|
||||
}
|
||||
|
||||
/**
|
||||
* If we have received an inbound connection in the last 2 minutes, don't allow
|
||||
* our IP to change.
|
||||
@ -333,14 +335,61 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
_lastInboundReceivedOn = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* From config, UPnP, local i/f, ...
|
||||
*
|
||||
* @param source used for logging only
|
||||
* @param ip publicly routable IPv4 only
|
||||
* @param port 0 if unknown
|
||||
*/
|
||||
public void externalAddressReceived(String source, byte[] ip, int port) {
|
||||
String s = RemoteHostId.toString(ip);
|
||||
if (_log.shouldLog(Log.WARN))
|
||||
_log.warn("Received address: " + s + " port: " + port + " from: " + source);
|
||||
if (explicitAddressSpecified())
|
||||
return;
|
||||
String sources = _context.getProperty(PROP_SOURCES, DEFAULT_SOURCES);
|
||||
if (!sources.contains(source))
|
||||
return;
|
||||
boolean changed = changeAddress(ip, port);
|
||||
// Assume if we have an interface with a public IP that we aren't firewalled.
|
||||
// If this is wrong, the peer test will figure it out and change the status.
|
||||
if (changed && source.equals(Transport.SOURCE_INTERFACE))
|
||||
setReachabilityStatus(CommSystemFacade.STATUS_OK);
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback from UPnP.
|
||||
* If we we have an IP address and UPnP claims success, believe it.
|
||||
* If this is wrong, the peer test will figure it out and change the status.
|
||||
* Don't do anything if UPnP claims failure.
|
||||
*/
|
||||
public void forwardPortStatus(int port, boolean success, String reason) {
|
||||
if (_log.shouldLog(Log.WARN)) {
|
||||
if (success)
|
||||
_log.warn("UPnP has opened the SSU port: " + port);
|
||||
else
|
||||
_log.warn("UPnP has failed to open the SSU port: " + port + " reason: " + reason);
|
||||
}
|
||||
if (success && _externalListenHost != null)
|
||||
setReachabilityStatus(CommSystemFacade.STATUS_OK);
|
||||
}
|
||||
|
||||
/**
|
||||
* Someone we tried to contact gave us what they think our IP address is.
|
||||
* Right now, we just blindly trust them, changing our IP and port on a
|
||||
* whim. this is not good ;)
|
||||
*
|
||||
* Todo:
|
||||
* - Much better tracking of troublemakers
|
||||
* - Disable if we have good local address or UPnP
|
||||
*
|
||||
* @param ip publicly routable IPv4 only
|
||||
* @param ourPort >= 1024
|
||||
*/
|
||||
void externalAddressReceived(Hash from, byte ourIP[], int ourPort) {
|
||||
boolean isValid = isValid(ourIP);
|
||||
boolean isValid = isValid(ourIP) &&
|
||||
(ourPort >= MIN_EXTERNAL_PORT || ourPort == _externalListenPort || _externalListenPort <= 0);
|
||||
boolean explicitSpecified = explicitAddressSpecified();
|
||||
boolean inboundRecent = _lastInboundReceivedOn + ALLOW_IP_CHANGE_INTERVAL > System.currentTimeMillis();
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
@ -350,15 +399,15 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
|
||||
if (explicitSpecified)
|
||||
return;
|
||||
String sources = _context.getProperty(PROP_SOURCES, DEFAULT_SOURCES);
|
||||
if (!sources.contains("ssu"))
|
||||
return;
|
||||
|
||||
boolean fixedPort = getIsPortFixed();
|
||||
boolean updated = false;
|
||||
boolean fireTest = false;
|
||||
if (!isValid) {
|
||||
// ignore them
|
||||
if (_log.shouldLog(Log.ERROR))
|
||||
_log.error("The router " + from.toBase64() + " told us we have an invalid IP - "
|
||||
+ RemoteHostId.toString(ourIP) + ". Lets throw tomatoes at them");
|
||||
+ RemoteHostId.toString(ourIP) + " port " + ourPort + ". Lets throw tomatoes at them");
|
||||
markUnreachable(from);
|
||||
//_context.shitlist().shitlistRouter(from, "They said we had an invalid IP", STYLE);
|
||||
return;
|
||||
@ -367,10 +416,24 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Ignoring IP address suggestion, since we have received an inbound con recently");
|
||||
} else {
|
||||
changeAddress(ourIP, ourPort);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ourPort >= 1024 or 0 for no change
|
||||
*/
|
||||
private boolean changeAddress(byte ourIP[], int ourPort) {
|
||||
/** this defaults to true, which means we never change our external port based on what somebody tells us */
|
||||
boolean fixedPort = getIsPortFixed();
|
||||
boolean updated = false;
|
||||
boolean fireTest = false;
|
||||
|
||||
synchronized (this) {
|
||||
if ( (_externalListenHost == null) ||
|
||||
(!eq(_externalListenHost.getAddress(), _externalListenPort, ourIP, ourPort)) ) {
|
||||
if ( (_reachabilityStatus == CommSystemFacade.STATUS_UNKNOWN) ||
|
||||
if ( (_reachabilityStatus != CommSystemFacade.STATUS_OK) ||
|
||||
(_externalListenHost == null) || (_externalListenPort <= 0) ||
|
||||
(_context.clock().now() - _reachabilityStatusLastUpdated > 2*TEST_FREQUENCY) ) {
|
||||
// they told us something different and our tests are either old or failing
|
||||
@ -378,11 +441,14 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
_log.info("Trying to change our external address...");
|
||||
try {
|
||||
_externalListenHost = InetAddress.getByAddress(ourIP);
|
||||
if (!fixedPort)
|
||||
// fixed port defaults to true so we never do this
|
||||
if (ourPort >= MIN_EXTERNAL_PORT && !fixedPort)
|
||||
_externalListenPort = ourPort;
|
||||
rebuildExternalAddress();
|
||||
replaceAddress(_externalAddress);
|
||||
updated = true;
|
||||
if (_externalListenPort > 0) {
|
||||
rebuildExternalAddress();
|
||||
replaceAddress(_externalAddress);
|
||||
updated = true;
|
||||
}
|
||||
} catch (UnknownHostException uhe) {
|
||||
_externalListenHost = null;
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
@ -401,23 +467,24 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
_log.info("Same address as the current one");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (fireTest) {
|
||||
_context.statManager().addRateData("udp.addressTestInsteadOfUpdate", 1, 0);
|
||||
_testEvent.forceRun();
|
||||
SimpleTimer.getInstance().addEvent(_testEvent, 5*1000);
|
||||
} else if (updated) {
|
||||
_context.statManager().addRateData("udp.addressUpdated", 1, 0);
|
||||
if (!fixedPort)
|
||||
_context.router().setConfigSetting(PROP_EXTERNAL_PORT, ourPort+"");
|
||||
// store these for laptop-mode (change ident on restart... or every time... when IP changes)
|
||||
_context.router().setConfigSetting(PROP_IP, _externalListenHost.getHostAddress());
|
||||
_context.router().setConfigSetting(PROP_IP_CHANGE, "" + _context.clock().now());
|
||||
_context.router().saveConfig();
|
||||
_context.router().rebuildRouterInfo();
|
||||
_testEvent.forceRun();
|
||||
SimpleTimer.getInstance().addEvent(_testEvent, 5*1000);
|
||||
}
|
||||
_testEvent.forceRun();
|
||||
SimpleTimer.getInstance().addEvent(_testEvent, 5*1000);
|
||||
return updated;
|
||||
}
|
||||
|
||||
|
||||
private static final boolean eq(byte laddr[], int lport, byte raddr[], int rport) {
|
||||
return (rport == lport) && DataHelper.eq(laddr, raddr);
|
||||
}
|
||||
@ -427,7 +494,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
if (addr.length < 4) return false;
|
||||
if (isPubliclyRoutable(addr))
|
||||
return true;
|
||||
return Boolean.valueOf(_context.getProperty("i2np.udp.allowLocal", "false")).booleanValue();
|
||||
return Boolean.valueOf(_context.getProperty("i2np.udp.allowLocal")).booleanValue();
|
||||
}
|
||||
|
||||
private boolean getIsPortFixed() {
|
||||
@ -589,12 +656,13 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
/*** infinite loop
|
||||
public RouterAddress getCurrentAddress() {
|
||||
if (needsRebuild())
|
||||
rebuildExternalAddress(false);
|
||||
return super.getCurrentAddress();
|
||||
}
|
||||
***/
|
||||
|
||||
@Override
|
||||
public void messageReceived(I2NPMessage inMsg, RouterIdentity remoteIdent, Hash remoteIdentHash, long msToReceive, int bytesReceived) {
|
||||
@ -861,6 +929,10 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
}
|
||||
|
||||
public TransportBid bid(RouterInfo toAddress, long dataSize) {
|
||||
if (dataSize > OutboundMessageState.MAX_MSG_SIZE) {
|
||||
// NTCP max is lower, so msg will get dropped
|
||||
return null;
|
||||
}
|
||||
Hash to = toAddress.getIdentity().calculateHash();
|
||||
PeerState peer = getPeerState(to);
|
||||
if (peer != null) {
|
||||
@ -999,6 +1071,9 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
|
||||
public void stopListening() {
|
||||
shutdown();
|
||||
// will this work?
|
||||
_externalAddress = null;
|
||||
replaceAddress(null);
|
||||
}
|
||||
|
||||
private boolean explicitAddressSpecified() {
|
||||
@ -1009,14 +1084,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
void rebuildExternalAddress(boolean allowRebuildRouterInfo) {
|
||||
// if the external port is specified, we want to use that to bind to even
|
||||
// if we don't know the external host.
|
||||
String port = _context.getProperty(PROP_EXTERNAL_PORT);
|
||||
if (port != null) {
|
||||
try {
|
||||
_externalListenPort = Integer.parseInt(port);
|
||||
} catch (NumberFormatException nfe) {
|
||||
_externalListenPort = -1;
|
||||
}
|
||||
}
|
||||
_externalListenPort = _context.getProperty(PROP_EXTERNAL_PORT, -1);
|
||||
|
||||
if (explicitAddressSpecified()) {
|
||||
try {
|
||||
@ -1112,12 +1180,18 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
}
|
||||
|
||||
public boolean introducersRequired() {
|
||||
/******************
|
||||
* Don't do this anymore, as we are removing the checkbox from the UI,
|
||||
* and we rarely if ever see the problem of false negatives for firewall detection -
|
||||
* it's usually false positives.
|
||||
******************
|
||||
String forceIntroducers = _context.getProperty(PROP_FORCE_INTRODUCERS);
|
||||
if ( (forceIntroducers != null) && (Boolean.valueOf(forceIntroducers).booleanValue()) ) {
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Force introducers specified");
|
||||
return true;
|
||||
}
|
||||
*******************/
|
||||
short status = getReachabilityStatus();
|
||||
switch (status) {
|
||||
case CommSystemFacade.STATUS_REJECT_UNSOLICITED:
|
||||
@ -1135,6 +1209,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
}
|
||||
}
|
||||
|
||||
/** default true */
|
||||
private boolean allowDirectUDP() {
|
||||
String allowDirect = _context.getProperty(PROP_ALLOW_DIRECT);
|
||||
return ( (allowDirect == null) || (Boolean.valueOf(allowDirect).booleanValue()) );
|
||||
@ -1166,8 +1241,8 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
// + " lastSentFully: " + sendDelay
|
||||
// + " expired? " + msg.isExpired());
|
||||
consecutive = msg.getPeer().incrementConsecutiveFailedSends();
|
||||
if (_log.shouldLog(Log.WARN))
|
||||
_log.warn("Consecutive failure #" + consecutive
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Consecutive failure #" + consecutive
|
||||
+ " on " + msg.toString()
|
||||
+ " to " + msg.getPeer());
|
||||
if ( (_context.clock().now() - msg.getPeer().getLastSendFullyTime() <= 60*1000) || (consecutive < MAX_CONSECUTIVE_FAILED) ) {
|
||||
@ -1187,6 +1262,9 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
}
|
||||
|
||||
private void noteSend(OutboundMessageState msg, boolean successful) {
|
||||
// bail before we do all the work
|
||||
if (!_context.messageHistory().getDoLog())
|
||||
return;
|
||||
int pushCount = msg.getPushCount();
|
||||
int sends = msg.getMaxSends();
|
||||
boolean expired = msg.isExpired();
|
||||
@ -1223,10 +1301,11 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
|
||||
public void failed(OutNetMessage msg, String reason) {
|
||||
if (msg == null) return;
|
||||
if (_log.shouldLog(Log.WARN))
|
||||
_log.warn("Sending message failed: " + msg, new Exception("failed from"));
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Sending message failed: " + msg, new Exception("failed from"));
|
||||
|
||||
_context.messageHistory().sendMessage(msg.getMessageType(), msg.getMessageId(), msg.getExpiration(),
|
||||
if (!_context.messageHistory().getDoLog())
|
||||
_context.messageHistory().sendMessage(msg.getMessageType(), msg.getMessageId(), msg.getExpiration(),
|
||||
msg.getTarget().getIdentity().calculateHash(), false, reason);
|
||||
super.afterSend(msg, false);
|
||||
}
|
||||
@ -1678,7 +1757,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
buf.append(" V ");
|
||||
else
|
||||
buf.append(" <a href=\"").append(urlBase).append("?sort=0\">V</a> ");
|
||||
buf.append("</td><td><b><a href=\"#def.idle\">idle</a></b>");
|
||||
buf.append("</td><td>dir/intro</td><td><b><a href=\"#def.idle\">idle</a></b>");
|
||||
appendSortLinks(buf, urlBase, sortFlags, "Sort by idle inbound", FLAG_IDLE_IN);
|
||||
buf.append("/");
|
||||
appendSortLinks(buf, urlBase, sortFlags, "Sort by idle outbound", FLAG_IDLE_OUT);
|
||||
@ -1734,32 +1813,11 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
buf.append(name);
|
||||
buf.append("\">");
|
||||
buf.append(name);
|
||||
/*
|
||||
buf.append("@");
|
||||
byte ip[] = peer.getRemoteIP();
|
||||
for (int j = 0; j < ip.length; j++) {
|
||||
int num = ip[j] & 0xFF;
|
||||
if (num < 10)
|
||||
buf.append("00");
|
||||
else if (num < 100)
|
||||
buf.append("0");
|
||||
buf.append(num);
|
||||
if (j + 1 < ip.length)
|
||||
buf.append('.');
|
||||
}
|
||||
buf.append(':');
|
||||
int port = peer.getRemotePort();
|
||||
if (port < 10)
|
||||
buf.append("0000");
|
||||
else if (port < 100)
|
||||
buf.append("000");
|
||||
else if (port < 1000)
|
||||
buf.append("00");
|
||||
else if (port < 10000)
|
||||
buf.append("0");
|
||||
buf.append(port);
|
||||
*/
|
||||
buf.append("</a> ");
|
||||
buf.append("</a>");
|
||||
//byte ip[] = peer.getRemoteIP();
|
||||
//if (ip != null)
|
||||
// buf.append(' ').append(_context.blocklist().toStr(ip));
|
||||
buf.append("</td><td>");
|
||||
if (peer.isInbound())
|
||||
buf.append("in ");
|
||||
else
|
||||
@ -1915,8 +1973,8 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
numPeers++;
|
||||
}
|
||||
|
||||
buf.append("<tr><td colspan=\"15\"><hr /></td></tr>\n");
|
||||
buf.append(" <tr><td colspan=\"2\"><b>Total</b></td>");
|
||||
buf.append("<tr><td colspan=\"16\"><hr /></td></tr>\n");
|
||||
buf.append(" <tr><td colspan=\"3\"><b>Total</b></td>");
|
||||
buf.append(" <td align=\"right\">");
|
||||
buf.append(formatKBps(bpsIn)).append("/").append(formatKBps(bpsOut));
|
||||
buf.append("KBps</td>");
|
||||
@ -2105,7 +2163,10 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
|
||||
if ( (status != old) && (status != CommSystemFacade.STATUS_UNKNOWN) ) {
|
||||
if (_log.shouldLog(Log.INFO))
|
||||
_log.info("Old status: " + old + " New status: " + status + " from: ", new Exception("traceback"));
|
||||
if (needsRebuild())
|
||||
// Always rebuild when the status changes, even if our address hasn't changed,
|
||||
// as rebuildExternalAddress() calls replaceAddress() which calls CSFI.notifyReplaceAddress()
|
||||
// which will start up NTCP inbound when we transition to OK.
|
||||
// if (needsRebuild())
|
||||
rebuildExternalAddress();
|
||||
}
|
||||
}
|
||||
|
165
router/java/src/org/cybergarage/http/Date.java
Normal file
165
router/java/src/org/cybergarage/http/Date.java
Normal file
@ -0,0 +1,165 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File : Date.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/05/03
|
||||
* - first revision
|
||||
* 10/20/04
|
||||
* - Theo Beisch <theo.beisch@gmx.de>
|
||||
* - Fixed the following methods to use HOUR_OF_DAY instead of HOUR.
|
||||
* getHour(), getDateString() getTimeString()
|
||||
* - Fixed getInstance() to return GMT instance.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class Date
|
||||
{
|
||||
private Calendar cal;
|
||||
|
||||
public Date(Calendar cal)
|
||||
{
|
||||
this.cal = cal;
|
||||
}
|
||||
|
||||
public Calendar getCalendar()
|
||||
{
|
||||
return cal;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Time
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public int getHour()
|
||||
{
|
||||
// Thanks for Theo Beisch (10/20/04)
|
||||
return getCalendar().get(Calendar.HOUR_OF_DAY);
|
||||
}
|
||||
|
||||
public int getMinute()
|
||||
{
|
||||
return getCalendar().get(Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public int getSecond()
|
||||
{
|
||||
return getCalendar().get(Calendar.SECOND);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// paint
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static Date getLocalInstance()
|
||||
{
|
||||
return new Date(Calendar.getInstance());
|
||||
}
|
||||
|
||||
public final static Date getInstance()
|
||||
{
|
||||
// Thanks for Theo Beisch (10/20/04)
|
||||
return new Date(Calendar.getInstance(TimeZone.getTimeZone("GMT")));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getDateString
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String toDateString(int value)
|
||||
{
|
||||
if (value < 10)
|
||||
return "0" + Integer.toString(value);
|
||||
return Integer.toString(value);
|
||||
}
|
||||
|
||||
private final static String MONTH_STRING[] = {
|
||||
"Jan",
|
||||
"Feb",
|
||||
"Mar",
|
||||
"Apr",
|
||||
"May",
|
||||
"Jun",
|
||||
"Jul",
|
||||
"Aug",
|
||||
"Sep",
|
||||
"Oct",
|
||||
"Nov",
|
||||
"Dec",
|
||||
};
|
||||
|
||||
public final static String toMonthString(int value)
|
||||
{
|
||||
value -= Calendar.JANUARY;
|
||||
if (0 <= value && value < 12)
|
||||
return MONTH_STRING[value];
|
||||
return "";
|
||||
}
|
||||
|
||||
private final static String WEEK_STRING[] = {
|
||||
"Sun",
|
||||
"Mon",
|
||||
"Tue",
|
||||
"Wed",
|
||||
"Thu",
|
||||
"Fri",
|
||||
"Sat",
|
||||
};
|
||||
|
||||
public final static String toWeekString(int value)
|
||||
{
|
||||
value -= Calendar.SUNDAY;
|
||||
if (0 <= value && value < 7)
|
||||
return WEEK_STRING[value];
|
||||
return "";
|
||||
}
|
||||
|
||||
public final static String toTimeString(int value)
|
||||
{
|
||||
String str = "";
|
||||
if (value < 10)
|
||||
str += "0";
|
||||
str += Integer.toString(value);
|
||||
return str;
|
||||
}
|
||||
|
||||
public String getDateString()
|
||||
{
|
||||
// Thanks for Theo Beisch (10/20/04)
|
||||
Calendar cal = getCalendar();
|
||||
return
|
||||
toWeekString(cal.get(Calendar.DAY_OF_WEEK)) +", " +
|
||||
toTimeString(cal.get(Calendar.DATE)) + " " +
|
||||
toMonthString(cal.get(Calendar.MONTH)) + " " +
|
||||
Integer.toString(cal.get(Calendar.YEAR)) + " " +
|
||||
toTimeString(cal.get(Calendar.HOUR_OF_DAY)) + ":" +
|
||||
toTimeString(cal.get(Calendar.MINUTE)) + ":" +
|
||||
toTimeString(cal.get(Calendar.SECOND)) + " GMT";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getTimeString
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getTimeString()
|
||||
{
|
||||
// Thanks for Theo Beisch (10/20/04)
|
||||
Calendar cal = getCalendar();
|
||||
return
|
||||
toDateString(cal.get(Calendar.HOUR_OF_DAY)) +
|
||||
(((cal.get(Calendar.SECOND) % 2) == 0) ? ":" : " ") +
|
||||
toDateString(cal.get(Calendar.MINUTE));
|
||||
}
|
||||
|
||||
}
|
||||
|
22
router/java/src/org/cybergarage/http/HTML.java
Normal file
22
router/java/src/org/cybergarage/http/HTML.java
Normal file
@ -0,0 +1,22 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTML.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/05/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
public class HTML
|
||||
{
|
||||
public static final String CONTENT_TYPE = "text/html; charset=\"utf-8\"";
|
||||
}
|
||||
|
210
router/java/src/org/cybergarage/http/HTTP.java
Normal file
210
router/java/src/org/cybergarage/http/HTTP.java
Normal file
@ -0,0 +1,210 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: HTTP.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 08/30/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : the method getPort should return the default http port 80 when a port is not specified
|
||||
* - Description : the method is used in ControlRequest.setRequestHost() and in SubscriptionRequest.setService(). maybe the default port check could be done in these methods.
|
||||
* 09/03/02
|
||||
* - Added getRequestHostURL().
|
||||
* 03/11/04
|
||||
* - Added the following methods to send big content stream.
|
||||
* post(HTTPResponse, byte[])
|
||||
* post(HTTPResponse, InputStream)
|
||||
* 05/26/04
|
||||
* - Added NO_CATCH and MAX_AGE.
|
||||
* 10/20/04
|
||||
* - Brent Hills <bhills@openshores.com>
|
||||
* - Added Range and MYNAME;
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
public class HTTP
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static final String HOST = "HOST";
|
||||
|
||||
public static final String VERSION = "1.1";
|
||||
public static final String VERSION_10 = "1.0";
|
||||
public static final String VERSION_11 = "1.1";
|
||||
|
||||
public static final String CRLF = "\r\n";
|
||||
public static final String TAB = "\t";
|
||||
|
||||
public static final String SOAP_ACTION = "SOAPACTION";
|
||||
|
||||
public static final String M_SEARCH = "M-SEARCH";
|
||||
public static final String NOTIFY = "NOTIFY";
|
||||
public static final String POST = "POST";
|
||||
public static final String GET = "GET";
|
||||
public static final String HEAD = "HEAD";
|
||||
public static final String SUBSCRIBE = "SUBSCRIBE";
|
||||
public static final String UNSUBSCRIBE = "UNSUBSCRIBE";
|
||||
|
||||
public static final String DATE = "Date";
|
||||
public static final String CACHE_CONTROL = "Cache-Control";
|
||||
public static final String NO_CACHE = "no-cache";
|
||||
public static final String MAX_AGE = "max-age";
|
||||
public static final String CONNECTION = "Connection";
|
||||
public static final String CLOSE = "close";
|
||||
public static final String KEEP_ALIVE = "Keep-Alive";
|
||||
public static final String CONTENT_TYPE = "Content-Type";
|
||||
public static final String CONTENT_LENGTH = "Content-Length";
|
||||
public static final String CONTENT_RANGE = "Content-Range";
|
||||
public static final String CONTENT_RANGE_BYTES = "bytes";
|
||||
// Thanks for Brent Hills (10/20/04)
|
||||
public static final String RANGE = "Range";
|
||||
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
|
||||
public static final String CHUNKED = "Chunked";
|
||||
public static final String LOCATION = "Location";
|
||||
public static final String SERVER = "Server";
|
||||
|
||||
|
||||
public static final String ST = "ST";
|
||||
public static final String MX = "MX";
|
||||
public static final String MAN = "MAN";
|
||||
public static final String NT = "NT";
|
||||
public static final String NTS = "NTS";
|
||||
public static final String USN = "USN";
|
||||
public static final String EXT = "EXT";
|
||||
public static final String SID = "SID";
|
||||
public static final String SEQ = "SEQ";
|
||||
public final static String CALLBACK = "CALLBACK";
|
||||
public final static String TIMEOUT = "TIMEOUT";
|
||||
// Thanks for Brent Hills (10/20/04)
|
||||
public final static String MYNAME = "MYNAME";
|
||||
|
||||
public static final String REQEST_LINE_DELIM = " ";
|
||||
public static final String HEADER_LINE_DELIM = " :";
|
||||
public static final String STATUS_LINE_DELIM = " ";
|
||||
|
||||
public static final int DEFAULT_PORT = 80;
|
||||
public static final int DEFAULT_CHUNK_SIZE = 512 * 1024;
|
||||
public static final int DEFAULT_TIMEOUT = 30;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// URL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static final boolean isAbsoluteURL(String urlStr)
|
||||
{
|
||||
try {
|
||||
new URL(urlStr);
|
||||
return true;
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static final String getHost(String urlStr)
|
||||
{
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
return url.getHost();
|
||||
}
|
||||
catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static final int getPort(String urlStr)
|
||||
{
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (08/30/03)
|
||||
int port = url.getPort();
|
||||
if (port <= 0)
|
||||
port = DEFAULT_PORT;
|
||||
return port;
|
||||
}
|
||||
catch (Exception e) {
|
||||
return DEFAULT_PORT;
|
||||
}
|
||||
}
|
||||
|
||||
public static final String getRequestHostURL(String host, int port)
|
||||
{
|
||||
String reqHost = "http://" + host + ":" + port;
|
||||
return reqHost;
|
||||
}
|
||||
|
||||
public static final String toRelativeURL(String urlStr, boolean withParam)
|
||||
{
|
||||
String uri = urlStr;
|
||||
if (isAbsoluteURL(urlStr) == false) {
|
||||
if (0 < urlStr.length() && urlStr.charAt(0) != '/')
|
||||
uri = "/" + urlStr;
|
||||
}
|
||||
else {
|
||||
try{
|
||||
URL url = new URL(urlStr);
|
||||
uri = url.getPath();
|
||||
if (withParam == true) {
|
||||
String queryStr = url.getQuery();
|
||||
if (!queryStr.equals("")){
|
||||
uri += "?" + queryStr;
|
||||
}
|
||||
}
|
||||
if (uri.endsWith("/"))
|
||||
uri = uri.substring(0,uri.length()-1);
|
||||
}catch(Exception e){}
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
public static final String toRelativeURL(String urlStr)
|
||||
{
|
||||
return toRelativeURL(urlStr, true);
|
||||
}
|
||||
|
||||
public static final String getAbsoluteURL(String baseURLStr, String relURlStr)
|
||||
{
|
||||
try {
|
||||
URL baseURL = new URL(baseURLStr);
|
||||
String url =
|
||||
baseURL.getProtocol() + "://" +
|
||||
baseURL.getHost() + ":" +
|
||||
baseURL.getPort() +
|
||||
toRelativeURL(relURlStr);
|
||||
return url;
|
||||
}
|
||||
catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Chunk Size
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static int chunkSize = DEFAULT_CHUNK_SIZE;
|
||||
|
||||
public static final void setChunkSize(int size)
|
||||
{
|
||||
chunkSize = size;
|
||||
}
|
||||
|
||||
public static final int getChunkSize()
|
||||
{
|
||||
return chunkSize;
|
||||
}
|
||||
|
||||
}
|
||||
|
144
router/java/src/org/cybergarage/http/HTTPHeader.java
Normal file
144
router/java/src/org/cybergarage/http/HTTPHeader.java
Normal file
@ -0,0 +1,144 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: HTTPHeader.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/19/02
|
||||
* - first revision.
|
||||
* 05/26/04
|
||||
* - Jan Newmarch <jan.newmarch@infotech.monash.edu.au> (05/26/04)
|
||||
* - Fixed getValue() to compare using String::equals() instead of String::startWidth().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class HTTPHeader
|
||||
{
|
||||
private String name;
|
||||
private String value;
|
||||
|
||||
public HTTPHeader(String name, String value)
|
||||
{
|
||||
setName(name);
|
||||
setValue(value);
|
||||
}
|
||||
|
||||
public HTTPHeader(String lineStr)
|
||||
{
|
||||
setName("");
|
||||
setValue("");
|
||||
if (lineStr == null)
|
||||
return;
|
||||
int colonIdx = lineStr.indexOf(':');
|
||||
if (colonIdx < 0)
|
||||
return;
|
||||
String name = new String(lineStr.getBytes(), 0, colonIdx);
|
||||
String value = new String(lineStr.getBytes(), colonIdx+1, lineStr.length()-colonIdx-1);
|
||||
setName(name.trim());
|
||||
setValue(value.trim());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setName(String name)
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setValue(String value)
|
||||
{
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getValue()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
public boolean hasName()
|
||||
{
|
||||
if (name == null || name.length() <= 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// static methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String getValue(LineNumberReader reader, String name)
|
||||
{
|
||||
String bigName = name.toUpperCase();
|
||||
try {
|
||||
String lineStr = reader.readLine();
|
||||
while (lineStr != null && 0 < lineStr.length()) {
|
||||
HTTPHeader header = new HTTPHeader(lineStr);
|
||||
if (header.hasName() == false) {
|
||||
lineStr = reader.readLine();
|
||||
continue;
|
||||
}
|
||||
String bigLineHeaderName = header.getName().toUpperCase();
|
||||
// Thanks for Jan Newmarch <jan.newmarch@infotech.monash.edu.au> (05/26/04)
|
||||
if (bigLineHeaderName.equals(bigName) == false) {
|
||||
lineStr = reader.readLine();
|
||||
continue;
|
||||
}
|
||||
return header.getValue();
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
Debug.warning(e);
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public final static String getValue(String data, String name)
|
||||
{
|
||||
StringReader strReader = new StringReader(data);
|
||||
LineNumberReader lineReader = new LineNumberReader(strReader);
|
||||
return getValue(lineReader, name);
|
||||
}
|
||||
|
||||
public final static String getValue(byte[] data, String name)
|
||||
{
|
||||
return getValue(new String(data), name);
|
||||
}
|
||||
|
||||
public final static int getIntegerValue(String data, String name)
|
||||
{
|
||||
try {
|
||||
return Integer.parseInt(getValue(data, name));
|
||||
}
|
||||
catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public final static int getIntegerValue(byte[] data, String name)
|
||||
{
|
||||
try {
|
||||
return Integer.parseInt(getValue(data, name));
|
||||
}
|
||||
catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
808
router/java/src/org/cybergarage/http/HTTPPacket.java
Normal file
808
router/java/src/org/cybergarage/http/HTTPPacket.java
Normal file
@ -0,0 +1,808 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: HTTPConnection.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 09/02/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : The API is unable to receive responses from the Microsoft UPnP stack
|
||||
* - Error : the Microsoft UPnP stack is based on ISAPI on IIS, and whenever IIS
|
||||
* receives a post request, it answers with two responses: the first one has no
|
||||
* body and it is a code 100 (continue) response, which has to be ignored. The
|
||||
* second response is the actual one and should be parsed as the response.
|
||||
* 02/09/04
|
||||
* - Ralf G. R. Bergs" <Ralf@Ber.gs>
|
||||
* - Why do you strip leading and trailing white space from the response body?
|
||||
* - Disabled to trim the content string.
|
||||
* 03/11/04
|
||||
* - Added some methods about InputStream content.
|
||||
* setContentInputStream(), getContentInputStream() and hasContentInputStream().
|
||||
* 03/16/04
|
||||
* - Thanks for Darrell Young
|
||||
* - Added setVersion() and getVersion();
|
||||
* 03/17/04
|
||||
* - Added hasFirstLine();
|
||||
* 05/26/04
|
||||
* - Jan Newmarch <jan.newmarch@infotech.monash.edu.au> (05/26/04)
|
||||
* - Changed setCacheControl() and getChcheControl();
|
||||
* 08/25/04
|
||||
* - Added the following methods.
|
||||
* hasContentRange(), setContentRange(), getContentRange(),
|
||||
* getContentRangeFirstPosition(), getContentRangeLastPosition() and getContentRangeInstanceLength()
|
||||
* 08/26/04
|
||||
* - Added the following methods.
|
||||
* hasConnection(), setConnection(), getConnection(),
|
||||
* isCloseConnection() and isKeepAliveConnection()
|
||||
* 08/27/04
|
||||
* - Added a updateWithContentLength paramger to setContent().
|
||||
* - Changed to HTTPPacket::set() not to change the header of Content-Length.
|
||||
* 08/28/04
|
||||
* - Added init() and read().
|
||||
* 09/19/04
|
||||
* - Added a onlyHeaders parameter to set().
|
||||
* 10/20/04
|
||||
* - Brent Hills <bhills@openshores.com>
|
||||
* - Changed hasContentRange() to check Content-Range and Range header.
|
||||
* - Added support for Range header to getContentRange().
|
||||
* 02/02/05
|
||||
* - Mark Retallack <mretallack@users.sourceforge.net>
|
||||
* - Fixed set() not to read over the content length when the stream is keep alive.
|
||||
* 02/28/05
|
||||
* - Added the following methods for chunked stream support.
|
||||
* hasTransferEncoding(), setTransferEncoding(), getTransferEncoding(), isChunked().
|
||||
* 03/02/05
|
||||
* - Changed post() to suppot chunked stream.
|
||||
*
|
||||
*******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
import org.cybergarage.net.*;
|
||||
import org.cybergarage.util.*;
|
||||
import java.util.Calendar;
|
||||
|
||||
public class HTTPPacket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPPacket()
|
||||
{
|
||||
setVersion(HTTP.VERSION);
|
||||
setContentInputStream(null);
|
||||
}
|
||||
|
||||
public HTTPPacket(HTTPPacket httpPacket)
|
||||
{
|
||||
setVersion(HTTP.VERSION);
|
||||
set(httpPacket);
|
||||
setContentInputStream(null);
|
||||
}
|
||||
|
||||
public HTTPPacket(InputStream in)
|
||||
{
|
||||
setVersion(HTTP.VERSION);
|
||||
set(in);
|
||||
setContentInputStream(null);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// init
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void init()
|
||||
{
|
||||
setFirstLine("");
|
||||
clearHeaders();
|
||||
setContent(new byte[0], false);
|
||||
setContentInputStream(null);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Version
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String version;
|
||||
|
||||
public void setVersion(String ver)
|
||||
{
|
||||
version = ver;
|
||||
}
|
||||
|
||||
public String getVersion()
|
||||
{
|
||||
return version;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// set
|
||||
////////////////////////////////////////////////
|
||||
|
||||
protected boolean set(InputStream in, boolean onlyHeaders)
|
||||
{
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
|
||||
|
||||
String firstLine = reader.readLine();
|
||||
if (firstLine == null || firstLine.length() <= 0)
|
||||
return false;
|
||||
setFirstLine(firstLine);
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/03/03)
|
||||
HTTPStatus httpStatus = new HTTPStatus(firstLine);
|
||||
int statCode = httpStatus.getStatusCode();
|
||||
if (statCode == HTTPStatus.CONTINUE){
|
||||
//ad hoc code for managing iis non-standard behaviour
|
||||
//iis sends 100 code response and a 200 code response in the same
|
||||
//stream, so the code should check the presence of the actual
|
||||
//response in the stream.
|
||||
//skip all header lines
|
||||
String headerLine = reader.readLine();
|
||||
while ((headerLine != null) && (0 < headerLine.length()) ) {
|
||||
HTTPHeader header = new HTTPHeader(headerLine);
|
||||
if (header.hasName() == true)
|
||||
setHeader(header);
|
||||
headerLine = reader.readLine();
|
||||
}
|
||||
//look forward another first line
|
||||
String actualFirstLine = reader.readLine();
|
||||
if ((actualFirstLine != null) && (0 < actualFirstLine.length()) ) {
|
||||
//this is the actual first line
|
||||
setFirstLine(actualFirstLine);
|
||||
}else{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
String headerLine = reader.readLine();
|
||||
while ((headerLine != null) && (0 < headerLine.length()) ) {
|
||||
HTTPHeader header = new HTTPHeader(headerLine);
|
||||
if (header.hasName() == true)
|
||||
setHeader(header);
|
||||
headerLine = reader.readLine();
|
||||
}
|
||||
|
||||
if (onlyHeaders == true) {
|
||||
setContent("", false);
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isChunkedRequest = isChunked();
|
||||
|
||||
long contentLen = 0;
|
||||
if (isChunkedRequest == true) {
|
||||
try {
|
||||
String chunkSizeLine = reader.readLine();
|
||||
contentLen = Long.parseLong(new String(chunkSizeLine.getBytes(), 0, chunkSizeLine.length()-2));
|
||||
}
|
||||
catch (Exception e) {};
|
||||
}
|
||||
else
|
||||
contentLen = getContentLength();
|
||||
|
||||
StringBuilder contentBuf = new StringBuilder();
|
||||
|
||||
while (0 < contentLen) {
|
||||
int chunkSize = HTTP.getChunkSize();
|
||||
char readBuf[] = new char[chunkSize];
|
||||
long readCnt = 0;
|
||||
while (readCnt < contentLen) {
|
||||
try {
|
||||
// Thanks for Mark Retallack (02/02/05)
|
||||
long bufReadLen = contentLen - readCnt;
|
||||
if (chunkSize < bufReadLen)
|
||||
bufReadLen = chunkSize;
|
||||
int readLen = reader.read(readBuf, 0, (int)bufReadLen);
|
||||
if (readLen < 0)
|
||||
break;
|
||||
contentBuf.append(new String(readBuf, 0, readLen));
|
||||
readCnt += readLen;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.warning(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isChunkedRequest == true) {
|
||||
// skip CRLF
|
||||
long skipLen = 0;
|
||||
do {
|
||||
long skipCnt = reader.skip(HTTP.CRLF.length() - skipLen);
|
||||
if (skipCnt < 0)
|
||||
break;
|
||||
skipLen += skipCnt;
|
||||
} while (skipLen < HTTP.CRLF.length());
|
||||
// read next chunk size
|
||||
try {
|
||||
String chunkSizeLine = reader.readLine();
|
||||
contentLen = Long.parseLong(new String(chunkSizeLine.getBytes(), 0, chunkSizeLine.length()-2));
|
||||
}
|
||||
catch (Exception e) {
|
||||
contentLen = 0;
|
||||
};
|
||||
}
|
||||
else
|
||||
contentLen = 0;
|
||||
}
|
||||
|
||||
// Thanks for Ralf G. R. Bergs (02/09/04)
|
||||
String contentStr = contentBuf.toString();
|
||||
setContent(contentStr.getBytes(), false);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected boolean set(InputStream in)
|
||||
{
|
||||
return set(in, false);
|
||||
}
|
||||
|
||||
protected boolean set(HTTPSocket httpSock)
|
||||
{
|
||||
return set(httpSock.getInputStream());
|
||||
}
|
||||
|
||||
protected void set(HTTPPacket httpPacket)
|
||||
{
|
||||
setFirstLine(httpPacket.getFirstLine());
|
||||
|
||||
clearHeaders();
|
||||
int nHeaders = httpPacket.getNHeaders();
|
||||
for (int n=0; n<nHeaders; n++) {
|
||||
HTTPHeader header = httpPacket.getHeader(n);
|
||||
addHeader(header);
|
||||
}
|
||||
setContent(httpPacket.getContent());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// read
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean read(HTTPSocket httpSock)
|
||||
{
|
||||
init();
|
||||
return set(httpSock);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// String
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String firstLine = "";
|
||||
|
||||
private void setFirstLine(String value)
|
||||
{
|
||||
firstLine = value;
|
||||
}
|
||||
|
||||
protected String getFirstLine()
|
||||
{
|
||||
return firstLine;
|
||||
}
|
||||
|
||||
protected String getFirstLineToken(int num)
|
||||
{
|
||||
StringTokenizer st = new StringTokenizer(firstLine, HTTP.REQEST_LINE_DELIM);
|
||||
String lastToken = "";
|
||||
for (int n=0; n<=num; n++) {
|
||||
if (st.hasMoreTokens() == false)
|
||||
return "";
|
||||
lastToken = st.nextToken();
|
||||
}
|
||||
return lastToken;
|
||||
}
|
||||
|
||||
public boolean hasFirstLine()
|
||||
{
|
||||
return (0 < firstLine.length()) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Header
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Vector httpHeaderList = new Vector();
|
||||
|
||||
public int getNHeaders()
|
||||
{
|
||||
return httpHeaderList.size();
|
||||
}
|
||||
|
||||
public void addHeader(HTTPHeader header)
|
||||
{
|
||||
httpHeaderList.add(header);
|
||||
}
|
||||
|
||||
public void addHeader(String name, String value)
|
||||
{
|
||||
HTTPHeader header = new HTTPHeader(name, value);
|
||||
httpHeaderList.add(header);
|
||||
}
|
||||
|
||||
public HTTPHeader getHeader(int n)
|
||||
{
|
||||
return (HTTPHeader)httpHeaderList.get(n);
|
||||
}
|
||||
|
||||
public HTTPHeader getHeader(String name)
|
||||
{
|
||||
int nHeaders = getNHeaders();
|
||||
for (int n=0; n<nHeaders; n++) {
|
||||
HTTPHeader header = getHeader(n);
|
||||
String headerName = header.getName();
|
||||
if (headerName.equalsIgnoreCase(name) == true)
|
||||
return header;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void clearHeaders()
|
||||
{
|
||||
httpHeaderList.clear();
|
||||
httpHeaderList = new Vector();
|
||||
}
|
||||
|
||||
public boolean hasHeader(String name)
|
||||
{
|
||||
return (getHeader(name) != null) ? true : false;
|
||||
}
|
||||
|
||||
public void setHeader(String name, String value)
|
||||
{
|
||||
HTTPHeader header = getHeader(name);
|
||||
if (header != null) {
|
||||
header.setValue(value);
|
||||
return;
|
||||
}
|
||||
addHeader(name, value);
|
||||
}
|
||||
|
||||
public void setHeader(String name, int value)
|
||||
{
|
||||
setHeader(name, Integer.toString(value));
|
||||
}
|
||||
|
||||
public void setHeader(String name, long value)
|
||||
{
|
||||
setHeader(name, Long.toString(value));
|
||||
}
|
||||
|
||||
public void setHeader(HTTPHeader header)
|
||||
{
|
||||
setHeader(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
public String getHeaderValue(String name)
|
||||
{
|
||||
HTTPHeader header = getHeader(name);
|
||||
if (header == null)
|
||||
return "";
|
||||
return header.getValue();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// set*Value
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setStringHeader(String name, String value, String startWidth, String endWidth)
|
||||
{
|
||||
String headerValue = value;
|
||||
if (headerValue.startsWith(startWidth) == false)
|
||||
headerValue = startWidth + headerValue;
|
||||
if (headerValue.endsWith(endWidth) == false)
|
||||
headerValue = headerValue + endWidth;
|
||||
setHeader(name, headerValue);
|
||||
}
|
||||
|
||||
public void setStringHeader(String name, String value)
|
||||
{
|
||||
setStringHeader(name, value, "\"", "\"");
|
||||
}
|
||||
|
||||
public String getStringHeaderValue(String name, String startWidth, String endWidth)
|
||||
{
|
||||
String headerValue = getHeaderValue(name);
|
||||
if (headerValue.startsWith(startWidth) == true)
|
||||
headerValue = headerValue.substring(1, headerValue.length());
|
||||
if (headerValue.endsWith(endWidth) == true)
|
||||
headerValue = headerValue.substring(0, headerValue.length()-1);
|
||||
return headerValue;
|
||||
}
|
||||
|
||||
public String getStringHeaderValue(String name)
|
||||
{
|
||||
return getStringHeaderValue(name, "\"", "\"");
|
||||
}
|
||||
|
||||
public void setIntegerHeader(String name, int value)
|
||||
{
|
||||
setHeader(name, Integer.toString(value));
|
||||
}
|
||||
|
||||
public void setLongHeader(String name, long value)
|
||||
{
|
||||
setHeader(name, Long.toString(value));
|
||||
}
|
||||
|
||||
public int getIntegerHeaderValue(String name)
|
||||
{
|
||||
HTTPHeader header = getHeader(name);
|
||||
if (header == null)
|
||||
return 0;
|
||||
return StringUtil.toInteger(header.getValue());
|
||||
}
|
||||
|
||||
public long getLongHeaderValue(String name)
|
||||
{
|
||||
HTTPHeader header = getHeader(name);
|
||||
if (header == null)
|
||||
return 0;
|
||||
return StringUtil.toLong(header.getValue());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getHeader
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getHeaderString()
|
||||
{
|
||||
StringBuilder str = new StringBuilder();
|
||||
|
||||
int nHeaders = getNHeaders();
|
||||
for (int n=0; n<nHeaders; n++) {
|
||||
HTTPHeader header = getHeader(n);
|
||||
str.append(header.getName() + ": " + header.getValue() + HTTP.CRLF);
|
||||
}
|
||||
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Contents
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private byte content[] = new byte[0];
|
||||
|
||||
public void setContent(byte data[], boolean updateWithContentLength)
|
||||
{
|
||||
content = data;
|
||||
if (updateWithContentLength == true)
|
||||
setContentLength(data.length);
|
||||
}
|
||||
|
||||
public void setContent(byte data[])
|
||||
{
|
||||
setContent(data, true);
|
||||
}
|
||||
|
||||
public void setContent(String data, boolean updateWithContentLength)
|
||||
{
|
||||
setContent(data.getBytes(), updateWithContentLength);
|
||||
}
|
||||
|
||||
public void setContent(String data)
|
||||
{
|
||||
setContent(data, true);
|
||||
}
|
||||
|
||||
public byte []getContent()
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
public String getContentString()
|
||||
{
|
||||
return new String(content);
|
||||
}
|
||||
|
||||
public boolean hasContent()
|
||||
{
|
||||
return (content.length > 0) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Contents (InputStream)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private InputStream contentInput = null;
|
||||
|
||||
public void setContentInputStream(InputStream in)
|
||||
{
|
||||
contentInput = in;
|
||||
}
|
||||
|
||||
public InputStream getContentInputStream()
|
||||
{
|
||||
return contentInput;
|
||||
}
|
||||
|
||||
public boolean hasContentInputStream()
|
||||
{
|
||||
return (contentInput != null) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ContentType
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setContentType(String type)
|
||||
{
|
||||
setHeader(HTTP.CONTENT_TYPE, type);
|
||||
}
|
||||
|
||||
public String getContentType()
|
||||
{
|
||||
return getHeaderValue(HTTP.CONTENT_TYPE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ContentLength
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setContentLength(long len)
|
||||
{
|
||||
setLongHeader(HTTP.CONTENT_LENGTH, len);
|
||||
}
|
||||
|
||||
public long getContentLength()
|
||||
{
|
||||
return getLongHeaderValue(HTTP.CONTENT_LENGTH);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Connection
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean hasConnection()
|
||||
{
|
||||
return hasHeader(HTTP.CONNECTION);
|
||||
}
|
||||
|
||||
public void setConnection(String value)
|
||||
{
|
||||
setHeader(HTTP.CONNECTION, value);
|
||||
}
|
||||
|
||||
public String getConnection()
|
||||
{
|
||||
return getHeaderValue(HTTP.CONNECTION);
|
||||
}
|
||||
|
||||
public boolean isCloseConnection()
|
||||
{
|
||||
if (hasConnection() == false)
|
||||
return false;
|
||||
String connection = getConnection();
|
||||
if (connection == null)
|
||||
return false;
|
||||
return connection.equalsIgnoreCase(HTTP.CLOSE);
|
||||
}
|
||||
|
||||
public boolean isKeepAliveConnection()
|
||||
{
|
||||
if (hasConnection() == false)
|
||||
return false;
|
||||
String connection = getConnection();
|
||||
if (connection == null)
|
||||
return false;
|
||||
return connection.equalsIgnoreCase(HTTP.KEEP_ALIVE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ContentRange
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean hasContentRange()
|
||||
{
|
||||
return (hasHeader(HTTP.CONTENT_RANGE) || hasHeader(HTTP.RANGE));
|
||||
}
|
||||
|
||||
public void setContentRange(long firstPos, long lastPos, long length)
|
||||
{
|
||||
String rangeStr = "";
|
||||
rangeStr += HTTP.CONTENT_RANGE_BYTES + " ";
|
||||
rangeStr += Long.toString(firstPos) + "-";
|
||||
rangeStr += Long.toString(lastPos) + "/";
|
||||
rangeStr += ((0 < length) ? Long.toString(length) : "*");
|
||||
setHeader(HTTP.CONTENT_RANGE, rangeStr);
|
||||
}
|
||||
|
||||
public long[] getContentRange()
|
||||
{
|
||||
long range[] = new long[3];
|
||||
range[0] = range[1] = range[2] = 0;
|
||||
if (hasContentRange() == false)
|
||||
return range;
|
||||
String rangeLine = getHeaderValue(HTTP.CONTENT_RANGE);
|
||||
// Thanks for Brent Hills (10/20/04)
|
||||
if (rangeLine.length() <= 0)
|
||||
rangeLine = getHeaderValue(HTTP.RANGE);
|
||||
if (rangeLine.length() <= 0)
|
||||
return range;
|
||||
// Thanks for Brent Hills (10/20/04)
|
||||
StringTokenizer strToken = new StringTokenizer(rangeLine, " =");
|
||||
// Skip bytes
|
||||
if (strToken.hasMoreTokens() == false)
|
||||
return range;
|
||||
strToken.nextToken(" ");
|
||||
// Get first-byte-pos
|
||||
if (strToken.hasMoreTokens() == false)
|
||||
return range;
|
||||
String firstPosStr = strToken.nextToken(" -");
|
||||
try {
|
||||
range[0] = Long.parseLong(firstPosStr);
|
||||
}
|
||||
catch (NumberFormatException e) {};
|
||||
if (strToken.hasMoreTokens() == false)
|
||||
return range;
|
||||
String lastPosStr = strToken.nextToken("-/");
|
||||
try {
|
||||
range[1] = Long.parseLong(lastPosStr);
|
||||
}
|
||||
catch (NumberFormatException e) {};
|
||||
if (strToken.hasMoreTokens() == false)
|
||||
return range;
|
||||
String lengthStr = strToken.nextToken("/");
|
||||
try {
|
||||
range[2] = Long.parseLong(lengthStr);
|
||||
}
|
||||
catch (NumberFormatException e) {};
|
||||
return range;
|
||||
}
|
||||
|
||||
public long getContentRangeFirstPosition()
|
||||
{
|
||||
long range[] = getContentRange();
|
||||
return range[0];
|
||||
}
|
||||
|
||||
public long getContentRangeLastPosition()
|
||||
{
|
||||
long range[] = getContentRange();
|
||||
return range[1];
|
||||
}
|
||||
|
||||
public long getContentRangeInstanceLength()
|
||||
{
|
||||
long range[] = getContentRange();
|
||||
return range[2];
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// CacheControl
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setCacheControl(String directive)
|
||||
{
|
||||
setHeader(HTTP.CACHE_CONTROL, directive);
|
||||
}
|
||||
|
||||
public void setCacheControl(String directive, int value)
|
||||
{
|
||||
String strVal = directive + "=" + Integer.toString(value);
|
||||
setHeader(HTTP.CACHE_CONTROL, strVal);
|
||||
}
|
||||
|
||||
public void setCacheControl(int value)
|
||||
{
|
||||
setCacheControl(HTTP.MAX_AGE, value);
|
||||
}
|
||||
|
||||
public String getCacheControl()
|
||||
{
|
||||
return getHeaderValue(HTTP.CACHE_CONTROL);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Server
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setServer(String name)
|
||||
{
|
||||
setHeader(HTTP.SERVER, name);
|
||||
}
|
||||
|
||||
public String getServer()
|
||||
{
|
||||
return getHeaderValue(HTTP.SERVER);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Host
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setHost(String host, int port)
|
||||
{
|
||||
String hostAddr = host;
|
||||
if (HostInterface.isIPv6Address(host) == true)
|
||||
hostAddr = "[" + host + "]";
|
||||
setHeader(HTTP.HOST, hostAddr + ":" + Integer.toString(port));
|
||||
}
|
||||
|
||||
public String getHost()
|
||||
{
|
||||
return getHeaderValue(HTTP.HOST);
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Date
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setDate(Calendar cal)
|
||||
{
|
||||
Date date = new Date(cal);
|
||||
setHeader(HTTP.DATE, date.getDateString());
|
||||
}
|
||||
|
||||
public String getDate()
|
||||
{
|
||||
return getHeaderValue(HTTP.DATE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Connection
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean hasTransferEncoding()
|
||||
{
|
||||
return hasHeader(HTTP.TRANSFER_ENCODING);
|
||||
}
|
||||
|
||||
public void setTransferEncoding(String value)
|
||||
{
|
||||
setHeader(HTTP.TRANSFER_ENCODING, value);
|
||||
}
|
||||
|
||||
public String getTransferEncoding()
|
||||
{
|
||||
return getHeaderValue(HTTP.TRANSFER_ENCODING);
|
||||
}
|
||||
|
||||
public boolean isChunked()
|
||||
{
|
||||
if (hasTransferEncoding() == false)
|
||||
return false;
|
||||
String transEnc = getTransferEncoding();
|
||||
if (transEnc == null)
|
||||
return false;
|
||||
return transEnc.equalsIgnoreCase(HTTP.CHUNKED);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// set
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/*
|
||||
public final static boolean parse(HTTPPacket httpPacket, InputStream in)
|
||||
{
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
|
||||
return parse(httpPacket, reader);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
511
router/java/src/org/cybergarage/http/HTTPRequest.java
Normal file
511
router/java/src/org/cybergarage/http/HTTPRequest.java
Normal file
@ -0,0 +1,511 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: HTTPRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 05/23/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Add a relative URL check to setURI().
|
||||
* 09/02/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : Devices whose description use absolute urls receive wrong http requests
|
||||
* - Error : the presence of a base url is not mandatory, the API code makes the assumption that control and event subscription urls are relative
|
||||
* - Description: The method setURI should be changed as follows
|
||||
* 02/01/04
|
||||
* - Added URI parameter methods.
|
||||
* 03/16/04
|
||||
* - Removed setVersion() because the method is added to the super class.
|
||||
* - Changed getVersion() to return the version when the first line string has the length.
|
||||
* 05/19/04
|
||||
* - Changed post(HTTPResponse *) to close the socket stream from the server.
|
||||
* 08/19/04
|
||||
* - Fixed getFirstLineString() and getHTTPVersion() no to return "HTTP/HTTP/version".
|
||||
* 08/25/04
|
||||
* - Added isHeadRequest().
|
||||
* 08/26/04
|
||||
* - Changed post(HTTPResponse) not to close the connection.
|
||||
* - Changed post(String, int) to add a connection header to close.
|
||||
* 08/27/04
|
||||
* - Changed post(String, int) to support the persistent connection.
|
||||
* 08/28/04
|
||||
* - Added isKeepAlive().
|
||||
* 10/26/04
|
||||
* - Brent Hills <bhills@openshores.com>
|
||||
* - Added a fix to post() when the last position of Content-Range header is 0.
|
||||
* - Added a Content-Range header to the response in post().
|
||||
* - Changed the status code for the Content-Range request in post().
|
||||
* - Added to check the range of Content-Range request in post().
|
||||
* 03/02/05
|
||||
* - Changed post() to suppot chunked stream.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
|
||||
import org.cybergarage.util.Debug;
|
||||
|
||||
public class HTTPRequest extends HTTPPacket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public HTTPRequest(InputStream in)
|
||||
{
|
||||
super(in);
|
||||
}
|
||||
|
||||
public HTTPRequest(HTTPSocket httpSock)
|
||||
{
|
||||
this(httpSock.getInputStream());
|
||||
setSocket(httpSock);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Method
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String method = null;
|
||||
|
||||
public void setMethod(String value)
|
||||
{
|
||||
method = value;
|
||||
}
|
||||
|
||||
public String getMethod()
|
||||
{
|
||||
if (method != null)
|
||||
return method;
|
||||
return getFirstLineToken(0);
|
||||
}
|
||||
|
||||
public boolean isMethod(String method)
|
||||
{
|
||||
String headerMethod = getMethod();
|
||||
if (headerMethod == null)
|
||||
return false;
|
||||
return headerMethod.equalsIgnoreCase(method);
|
||||
}
|
||||
|
||||
public boolean isGetRequest()
|
||||
{
|
||||
return isMethod(HTTP.GET);
|
||||
}
|
||||
|
||||
public boolean isPostRequest()
|
||||
{
|
||||
return isMethod(HTTP.POST);
|
||||
}
|
||||
|
||||
public boolean isHeadRequest()
|
||||
{
|
||||
return isMethod(HTTP.HEAD);
|
||||
}
|
||||
|
||||
public boolean isSubscribeRequest()
|
||||
{
|
||||
return isMethod(HTTP.SUBSCRIBE);
|
||||
}
|
||||
|
||||
public boolean isUnsubscribeRequest()
|
||||
{
|
||||
return isMethod(HTTP.UNSUBSCRIBE);
|
||||
}
|
||||
|
||||
public boolean isNotifyRequest()
|
||||
{
|
||||
return isMethod(HTTP.NOTIFY);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// URI
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String uri = null;
|
||||
|
||||
public void setURI(String value, boolean isCheckRelativeURL)
|
||||
{
|
||||
uri = value;
|
||||
if (isCheckRelativeURL == false)
|
||||
return;
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/02/03)
|
||||
uri = HTTP.toRelativeURL(uri);
|
||||
}
|
||||
|
||||
public void setURI(String value)
|
||||
{
|
||||
setURI(value, false);
|
||||
}
|
||||
|
||||
public String getURI()
|
||||
{
|
||||
if (uri != null)
|
||||
return uri;
|
||||
return getFirstLineToken(1);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// URI Parameter
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ParameterList getParameterList()
|
||||
{
|
||||
ParameterList paramList = new ParameterList();
|
||||
String uri = getURI();
|
||||
if (uri == null)
|
||||
return paramList;
|
||||
int paramIdx = uri.indexOf('?');
|
||||
if (paramIdx < 0)
|
||||
return paramList;
|
||||
while (0 < paramIdx) {
|
||||
int eqIdx = uri.indexOf('=', (paramIdx+1));
|
||||
String name = uri.substring(paramIdx+1, eqIdx);
|
||||
int nextParamIdx = uri.indexOf('&', (eqIdx+1));
|
||||
String value = uri.substring(eqIdx+1, (0 < nextParamIdx) ? nextParamIdx : uri.length());
|
||||
Parameter param = new Parameter(name, value);
|
||||
paramList.add(param);
|
||||
paramIdx = nextParamIdx;
|
||||
}
|
||||
return paramList;
|
||||
}
|
||||
|
||||
public String getParameterValue(String name)
|
||||
{
|
||||
ParameterList paramList = getParameterList();
|
||||
return paramList.getValue(name);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SOAPAction
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean isSOAPAction()
|
||||
{
|
||||
return hasHeader(HTTP.SOAP_ACTION);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Host / Port
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String requestHost = "";
|
||||
|
||||
public void setRequestHost(String host)
|
||||
{
|
||||
requestHost = host;
|
||||
}
|
||||
|
||||
public String getRequestHost()
|
||||
{
|
||||
return requestHost;
|
||||
}
|
||||
|
||||
private int requestPort = -1;
|
||||
|
||||
public void setRequestPort(int host)
|
||||
{
|
||||
requestPort = host;
|
||||
}
|
||||
|
||||
public int getRequestPort()
|
||||
{
|
||||
return requestPort;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Socket
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private HTTPSocket httpSocket = null;
|
||||
|
||||
public void setSocket(HTTPSocket value)
|
||||
{
|
||||
httpSocket = value;
|
||||
}
|
||||
|
||||
public HTTPSocket getSocket()
|
||||
{
|
||||
return httpSocket;
|
||||
}
|
||||
|
||||
/////////////////////////// /////////////////////
|
||||
// local address/port
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getLocalAddress()
|
||||
{
|
||||
return getSocket().getLocalAddress();
|
||||
}
|
||||
|
||||
public int getLocalPort()
|
||||
{
|
||||
return getSocket().getLocalPort();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// parseRequest
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean parseRequestLine(String lineStr)
|
||||
{
|
||||
StringTokenizer st = new StringTokenizer(lineStr, HTTP.REQEST_LINE_DELIM);
|
||||
if (st.hasMoreTokens() == false)
|
||||
return false;
|
||||
setMethod(st.nextToken());
|
||||
if (st.hasMoreTokens() == false)
|
||||
return false;
|
||||
setURI(st.nextToken());
|
||||
if (st.hasMoreTokens() == false)
|
||||
return false;
|
||||
setVersion(st.nextToken());
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// First Line
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getHTTPVersion()
|
||||
{
|
||||
if (hasFirstLine() == true)
|
||||
return getFirstLineToken(2);
|
||||
return "HTTP/" + super.getVersion();
|
||||
}
|
||||
|
||||
public String getFirstLineString()
|
||||
{
|
||||
return getMethod() + " " + getURI() + " " + getHTTPVersion() + HTTP.CRLF;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getHeader
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getHeader()
|
||||
{
|
||||
StringBuilder str = new StringBuilder();
|
||||
|
||||
str.append(getFirstLineString());
|
||||
|
||||
String headerString = getHeaderString();
|
||||
str.append(headerString);
|
||||
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isKeepAlive
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean isKeepAlive()
|
||||
{
|
||||
if (isCloseConnection() == true)
|
||||
return false;
|
||||
if (isKeepAliveConnection() == true)
|
||||
return true;
|
||||
String httpVer = getHTTPVersion();
|
||||
boolean isHTTP10 = (0 < httpVer.indexOf("1.0")) ? true : false;
|
||||
if (isHTTP10 == true)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// read
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean read()
|
||||
{
|
||||
return super.read(getSocket());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// POST (Response)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean post(HTTPResponse httpRes)
|
||||
{
|
||||
HTTPSocket httpSock = getSocket();
|
||||
long offset = 0;
|
||||
long length = httpRes.getContentLength();
|
||||
if (hasContentRange() == true) {
|
||||
long firstPos = getContentRangeFirstPosition();
|
||||
long lastPos = getContentRangeLastPosition();
|
||||
|
||||
// Thanks for Brent Hills (10/26/04)
|
||||
if (lastPos <= 0)
|
||||
lastPos = length - 1;
|
||||
if ((firstPos > length ) || (lastPos > length))
|
||||
return returnResponse(HTTPStatus.INVALID_RANGE);
|
||||
httpRes.setContentRange(firstPos, lastPos, length);
|
||||
httpRes.setStatusCode(HTTPStatus.PARTIAL_CONTENT);
|
||||
|
||||
offset = firstPos;
|
||||
length = lastPos - firstPos + 1;
|
||||
}
|
||||
return httpSock.post(httpRes, offset, length, isHeadRequest());
|
||||
//httpSock.close();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// POST (Request)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Socket postSocket = null;
|
||||
|
||||
public HTTPResponse post(String host, int port, boolean isKeepAlive)
|
||||
{
|
||||
HTTPResponse httpRes = new HTTPResponse();
|
||||
|
||||
setConnection((isKeepAlive == true) ? HTTP.KEEP_ALIVE : HTTP.CLOSE);
|
||||
|
||||
boolean isHeaderRequest = isHeadRequest();
|
||||
|
||||
OutputStream out = null;
|
||||
InputStream in = null;
|
||||
|
||||
try {
|
||||
if (postSocket == null) {
|
||||
// Mod for I2P
|
||||
// We can't handle the default system soTimeout of 3 minutes or so
|
||||
// as when the device goes away, this hangs the display of peers.jsp
|
||||
// and who knows what else.
|
||||
// Set the timeout to be nice and short, the device should be local and fast.
|
||||
// If he can't get back to us in 2 seconds, forget it.
|
||||
// And set the soTimeout to 1 second (for reads).
|
||||
//postSocket = new Socket(host, port);
|
||||
postSocket = new Socket();
|
||||
postSocket.setSoTimeout(1000);
|
||||
SocketAddress sa = new InetSocketAddress(host, port);
|
||||
postSocket.connect(sa, 2000);
|
||||
}
|
||||
|
||||
out = postSocket.getOutputStream();
|
||||
PrintStream pout = new PrintStream(out);
|
||||
pout.print(getHeader());
|
||||
pout.print(HTTP.CRLF);
|
||||
|
||||
boolean isChunkedRequest = isChunked();
|
||||
|
||||
String content = getContentString();
|
||||
int contentLength = 0;
|
||||
if (content != null)
|
||||
contentLength = content.length();
|
||||
|
||||
if (0 < contentLength) {
|
||||
if (isChunkedRequest == true) {
|
||||
String chunSizeBuf = Long.toString(contentLength);
|
||||
pout.print(chunSizeBuf);
|
||||
pout.print(HTTP.CRLF);
|
||||
}
|
||||
pout.print(content);
|
||||
if (isChunkedRequest == true)
|
||||
pout.print(HTTP.CRLF);
|
||||
}
|
||||
|
||||
if (isChunkedRequest == true) {
|
||||
pout.print("0");
|
||||
pout.print(HTTP.CRLF);
|
||||
}
|
||||
|
||||
pout.flush();
|
||||
|
||||
in = postSocket.getInputStream();
|
||||
httpRes.set(in, isHeaderRequest);
|
||||
}
|
||||
catch (Exception e) {
|
||||
httpRes.setStatusCode(HTTPStatus.INTERNAL_SERVER_ERROR);
|
||||
// I2P addition
|
||||
Debug.warning(e);
|
||||
} finally {
|
||||
if (isKeepAlive == false) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (Exception e) {};
|
||||
if (in != null)
|
||||
try {
|
||||
out.close();
|
||||
} catch (Exception e) {};
|
||||
if (out != null)
|
||||
try {
|
||||
postSocket.close();
|
||||
} catch (Exception e) {};
|
||||
postSocket = null;
|
||||
}
|
||||
}
|
||||
|
||||
return httpRes;
|
||||
}
|
||||
|
||||
public HTTPResponse post(String host, int port)
|
||||
{
|
||||
return post(host, port, false);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// set
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void set(HTTPRequest httpReq)
|
||||
{
|
||||
set((HTTPPacket)httpReq);
|
||||
setSocket(httpReq.getSocket());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// OK/BAD_REQUEST
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean returnResponse(int statusCode)
|
||||
{
|
||||
HTTPResponse httpRes = new HTTPResponse();
|
||||
httpRes.setStatusCode(statusCode);
|
||||
httpRes.setContentLength(0);
|
||||
return post(httpRes);
|
||||
}
|
||||
|
||||
public boolean returnOK()
|
||||
{
|
||||
return returnResponse(HTTPStatus.OK);
|
||||
}
|
||||
|
||||
public boolean returnBadRequest()
|
||||
{
|
||||
return returnResponse(HTTPStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// toString
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String toString()
|
||||
{
|
||||
StringBuilder str = new StringBuilder();
|
||||
|
||||
str.append(getHeader());
|
||||
str.append(HTTP.CRLF);
|
||||
str.append(getContentString());
|
||||
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
public void print()
|
||||
{
|
||||
System.out.println(toString());
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: HTTPRequestListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/13/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
public interface HTTPRequestListener
|
||||
{
|
||||
public void httpRequestRecieved(HTTPRequest httpReq);
|
||||
}
|
115
router/java/src/org/cybergarage/http/HTTPResponse.java
Normal file
115
router/java/src/org/cybergarage/http/HTTPResponse.java
Normal file
@ -0,0 +1,115 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTTPResponse.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 10/22/03
|
||||
* - Changed to initialize a content length header.
|
||||
* 10/22/04
|
||||
* - Added isSuccessful().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class HTTPResponse extends HTTPPacket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPResponse()
|
||||
{
|
||||
setContentType(HTML.CONTENT_TYPE);
|
||||
setServer(HTTPServer.getName());
|
||||
setContent("");
|
||||
}
|
||||
|
||||
public HTTPResponse(HTTPResponse httpRes)
|
||||
{
|
||||
set(httpRes);
|
||||
}
|
||||
|
||||
public HTTPResponse(InputStream in)
|
||||
{
|
||||
super(in);
|
||||
}
|
||||
|
||||
public HTTPResponse(HTTPSocket httpSock)
|
||||
{
|
||||
this(httpSock.getInputStream());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Status Line
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private int statusCode = 0;
|
||||
|
||||
public void setStatusCode(int code)
|
||||
{
|
||||
statusCode = code;
|
||||
}
|
||||
|
||||
public int getStatusCode()
|
||||
{
|
||||
if (statusCode != 0)
|
||||
return statusCode;
|
||||
HTTPStatus httpStatus = new HTTPStatus(getFirstLine());
|
||||
return httpStatus.getStatusCode();
|
||||
}
|
||||
|
||||
public boolean isSuccessful()
|
||||
{
|
||||
return HTTPStatus.isSuccessful(getStatusCode());
|
||||
}
|
||||
|
||||
public String getStatusLineString()
|
||||
{
|
||||
return "HTTP/" + getVersion() + " " + getStatusCode() + " " + HTTPStatus.code2String(statusCode) + HTTP.CRLF;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getHeader
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getHeader()
|
||||
{
|
||||
StringBuilder str = new StringBuilder();
|
||||
|
||||
str.append(getStatusLineString());
|
||||
str.append(getHeaderString());
|
||||
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// toString
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String toString()
|
||||
{
|
||||
StringBuilder str = new StringBuilder();
|
||||
|
||||
str.append(getStatusLineString());
|
||||
str.append(getHeaderString());
|
||||
str.append(HTTP.CRLF);
|
||||
str.append(getContentString());
|
||||
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
public void print()
|
||||
{
|
||||
System.out.println(toString());
|
||||
}
|
||||
}
|
204
router/java/src/org/cybergarage/http/HTTPServer.java
Normal file
204
router/java/src/org/cybergarage/http/HTTPServer.java
Normal file
@ -0,0 +1,204 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTTPServer.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/12/02
|
||||
* - first revision.
|
||||
* 10/20/03
|
||||
* - Improved the HTTP server using multithreading.
|
||||
* 08/27/04
|
||||
* - Changed accept() to set a default timeout, HTTP.DEFAULT_TIMEOUT, to the socket.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class HTTPServer implements Runnable
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String NAME = "CyberHTTP";
|
||||
public final static String VERSION = "1.0";
|
||||
|
||||
public final static int DEFAULT_PORT = 80;
|
||||
|
||||
public static String getName()
|
||||
{
|
||||
String osName = System.getProperty("os.name");
|
||||
String osVer = System.getProperty("os.version");
|
||||
return osName + "/" + osVer + " " + NAME + "/" + VERSION;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPServer()
|
||||
{
|
||||
serverSock = null;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ServerSocket
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ServerSocket serverSock = null;
|
||||
private InetAddress bindAddr = null;
|
||||
private int bindPort = 0;
|
||||
|
||||
public ServerSocket getServerSock()
|
||||
{
|
||||
return serverSock;
|
||||
}
|
||||
|
||||
public String getBindAddress()
|
||||
{
|
||||
if (bindAddr == null)
|
||||
return "";
|
||||
return bindAddr.toString();
|
||||
}
|
||||
|
||||
public int getBindPort()
|
||||
{
|
||||
return bindPort;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// open/close
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean open(String addr, int port)
|
||||
{
|
||||
if (serverSock != null)
|
||||
return true;
|
||||
try {
|
||||
bindAddr = InetAddress.getByName(addr);
|
||||
bindPort = port;
|
||||
serverSock = new ServerSocket(bindPort, 0, bindAddr);
|
||||
serverSock.setSoTimeout(10*1000);
|
||||
}
|
||||
catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean close()
|
||||
{
|
||||
if (serverSock == null)
|
||||
return true;
|
||||
try {
|
||||
serverSock.close();
|
||||
serverSock = null;
|
||||
bindAddr = null;
|
||||
bindPort = 0;
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Socket accept()
|
||||
{
|
||||
if (serverSock == null)
|
||||
return null;
|
||||
try {
|
||||
Socket sock = serverSock.accept();
|
||||
sock.setSoTimeout(HTTP.DEFAULT_TIMEOUT * 1000);
|
||||
return sock;
|
||||
}
|
||||
catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isOpened()
|
||||
{
|
||||
return (serverSock != null) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// httpRequest
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ListenerList httpRequestListenerList = new ListenerList();
|
||||
|
||||
public void addRequestListener(HTTPRequestListener listener)
|
||||
{
|
||||
httpRequestListenerList.add(listener);
|
||||
}
|
||||
|
||||
public void removeRequestListener(HTTPRequestListener listener)
|
||||
{
|
||||
httpRequestListenerList.remove(listener);
|
||||
}
|
||||
|
||||
public void performRequestListener(HTTPRequest httpReq)
|
||||
{
|
||||
int listenerSize = httpRequestListenerList.size();
|
||||
for (int n=0; n<listenerSize; n++) {
|
||||
HTTPRequestListener listener = (HTTPRequestListener)httpRequestListenerList.get(n);
|
||||
listener.httpRequestRecieved(httpReq);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// run
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Thread httpServerThread = null;
|
||||
|
||||
public void run()
|
||||
{
|
||||
if (isOpened() == false)
|
||||
return;
|
||||
|
||||
Thread thisThread = Thread.currentThread();
|
||||
|
||||
while (httpServerThread == thisThread) {
|
||||
Thread.yield();
|
||||
Socket sock;
|
||||
try {
|
||||
//Debug.message("accept ...");
|
||||
sock = accept();
|
||||
if (sock != null)
|
||||
Debug.message("sock = " + sock.getRemoteSocketAddress());
|
||||
}
|
||||
catch (Exception e){
|
||||
Debug.warning(e);
|
||||
break;
|
||||
}
|
||||
HTTPServerThread httpServThread = new HTTPServerThread(this, sock);
|
||||
httpServThread.start();
|
||||
//Debug.message("httpServThread ...");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean start()
|
||||
{
|
||||
httpServerThread = new Thread(this, "UPnP-HTTPServer");
|
||||
httpServerThread.start();
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean stop()
|
||||
{
|
||||
httpServerThread = null;
|
||||
return true;
|
||||
}
|
||||
}
|
104
router/java/src/org/cybergarage/http/HTTPServerList.java
Normal file
104
router/java/src/org/cybergarage/http/HTTPServerList.java
Normal file
@ -0,0 +1,104 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTTPServerList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 05/08/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.cybergarage.net.*;
|
||||
|
||||
public class HTTPServerList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 2379889735659369065L;
|
||||
|
||||
public HTTPServerList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void addRequestListener(HTTPRequestListener listener)
|
||||
{
|
||||
int nServers = size();
|
||||
for (int n=0; n<nServers; n++) {
|
||||
HTTPServer server = getHTTPServer(n);
|
||||
server.addRequestListener(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public HTTPServer getHTTPServer(int n)
|
||||
{
|
||||
return (HTTPServer)get(n);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// open/close
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void close()
|
||||
{
|
||||
int nServers = size();
|
||||
for (int n=0; n<nServers; n++) {
|
||||
HTTPServer server = getHTTPServer(n);
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean open(int port)
|
||||
{
|
||||
int nHostAddrs = HostInterface.getNHostAddresses();
|
||||
for (int n=0; n<nHostAddrs; n++) {
|
||||
String bindAddr = HostInterface.getHostAddress(n);
|
||||
HTTPServer httpServer = new HTTPServer();
|
||||
if (httpServer.open(bindAddr, port) == false) {
|
||||
close();
|
||||
clear();
|
||||
return false;
|
||||
}
|
||||
add(httpServer);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// start/stop
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void start()
|
||||
{
|
||||
int nServers = size();
|
||||
for (int n=0; n<nServers; n++) {
|
||||
HTTPServer server = getHTTPServer(n);
|
||||
server.start();
|
||||
}
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
int nServers = size();
|
||||
for (int n=0; n<nServers; n++) {
|
||||
HTTPServer server = getHTTPServer(n);
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
54
router/java/src/org/cybergarage/http/HTTPServerThread.java
Normal file
54
router/java/src/org/cybergarage/http/HTTPServerThread.java
Normal file
@ -0,0 +1,54 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTTPServerThread.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 10/10/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
public class HTTPServerThread extends Thread
|
||||
{
|
||||
private HTTPServer httpServer;
|
||||
private Socket sock;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPServerThread(HTTPServer httpServer, Socket sock)
|
||||
{
|
||||
this.httpServer = httpServer;
|
||||
this.sock = sock;
|
||||
this.setDaemon(true);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// run
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void run()
|
||||
{
|
||||
HTTPSocket httpSock = new HTTPSocket(sock);
|
||||
if (httpSock.open() == false)
|
||||
return;
|
||||
HTTPRequest httpReq = new HTTPRequest();
|
||||
httpReq.setSocket(httpSock);
|
||||
while (httpReq.read() == true) {
|
||||
httpServer.performRequestListener(httpReq);
|
||||
if (httpReq.isKeepAlive() == false)
|
||||
break;
|
||||
}
|
||||
httpSock.close();
|
||||
}
|
||||
}
|
249
router/java/src/org/cybergarage/http/HTTPSocket.java
Normal file
249
router/java/src/org/cybergarage/http/HTTPSocket.java
Normal file
@ -0,0 +1,249 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: HTTPSocket.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/12/02
|
||||
* - first revision.
|
||||
* 03/11/04
|
||||
* - Added the following methods about chunk size.
|
||||
* setChunkSize(), getChunkSize().
|
||||
* 08/26/04
|
||||
* - Added a isOnlyHeader to post().
|
||||
* 03/02/05
|
||||
* - Changed post() to suppot chunked stream.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
|
||||
public class HTTPSocket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPSocket(Socket socket)
|
||||
{
|
||||
setSocket(socket);
|
||||
open();
|
||||
}
|
||||
|
||||
public HTTPSocket(HTTPSocket socket)
|
||||
{
|
||||
setSocket(socket.getSocket());
|
||||
setInputStream(socket.getInputStream());
|
||||
setOutputStream(socket.getOutputStream());
|
||||
}
|
||||
|
||||
public void finalize()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Socket
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Socket socket = null;
|
||||
|
||||
private void setSocket(Socket socket)
|
||||
{
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
public Socket getSocket()
|
||||
{
|
||||
return socket;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// local address/port
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getLocalAddress()
|
||||
{
|
||||
return getSocket().getLocalAddress().getHostAddress();
|
||||
}
|
||||
|
||||
public int getLocalPort()
|
||||
{
|
||||
return getSocket().getLocalPort();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// in/out
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private InputStream sockIn = null;
|
||||
private OutputStream sockOut = null;
|
||||
|
||||
private void setInputStream(InputStream in)
|
||||
{
|
||||
sockIn = in;
|
||||
}
|
||||
|
||||
public InputStream getInputStream()
|
||||
{
|
||||
return sockIn;
|
||||
}
|
||||
|
||||
private void setOutputStream(OutputStream out)
|
||||
{
|
||||
sockOut = out;
|
||||
}
|
||||
|
||||
private OutputStream getOutputStream()
|
||||
{
|
||||
return sockOut;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// open/close
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean open()
|
||||
{
|
||||
Socket sock = getSocket();
|
||||
try {
|
||||
sockIn = sock.getInputStream();
|
||||
sockOut = sock.getOutputStream();
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean close()
|
||||
{
|
||||
try {
|
||||
if (sockIn != null)
|
||||
sockIn.close();
|
||||
if (sockOut != null)
|
||||
sockOut.close();
|
||||
getSocket().close();
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private boolean post(HTTPResponse httpRes, byte content[], long contentOffset, long contentLength, boolean isOnlyHeader)
|
||||
{
|
||||
httpRes.setDate(Calendar.getInstance());
|
||||
OutputStream out = getOutputStream();
|
||||
|
||||
try {
|
||||
httpRes.setContentLength(contentLength);
|
||||
|
||||
out.write(httpRes.getHeader().getBytes());
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
if (isOnlyHeader == true) {
|
||||
out.flush();
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isChunkedResponse = httpRes.isChunked();
|
||||
|
||||
if (isChunkedResponse == true) {
|
||||
String chunSizeBuf = Long.toString(contentLength);
|
||||
out.write(chunSizeBuf.getBytes());
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
}
|
||||
|
||||
out.write(content, (int)contentOffset, (int)contentLength);
|
||||
|
||||
if (isChunkedResponse == true) {
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
out.write("0".getBytes());
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
}
|
||||
|
||||
out.flush();
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean post(HTTPResponse httpRes, InputStream in, long contentOffset, long contentLength, boolean isOnlyHeader)
|
||||
{
|
||||
httpRes.setDate(Calendar.getInstance());
|
||||
OutputStream out = getOutputStream();
|
||||
|
||||
try {
|
||||
httpRes.setContentLength(contentLength);
|
||||
|
||||
out.write(httpRes.getHeader().getBytes());
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
|
||||
if (isOnlyHeader == true) {
|
||||
out.flush();
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isChunkedResponse = httpRes.isChunked();
|
||||
|
||||
if (0 < contentOffset)
|
||||
in.skip(contentOffset);
|
||||
|
||||
int chunkSize = HTTP.getChunkSize();
|
||||
byte readBuf[] = new byte[chunkSize];
|
||||
long readCnt = 0;
|
||||
long readSize = (chunkSize < contentLength) ? chunkSize : contentLength;
|
||||
int readLen = in.read(readBuf, 0, (int)readSize);
|
||||
while (0 < readLen && readCnt < contentLength) {
|
||||
if (isChunkedResponse == true) {
|
||||
String chunSizeBuf = Long.toString(readLen);
|
||||
out.write(chunSizeBuf.getBytes());
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
}
|
||||
out.write(readBuf, 0, readLen);
|
||||
if (isChunkedResponse == true)
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
readCnt += readLen;
|
||||
readSize = (chunkSize < (contentLength-readCnt)) ? chunkSize : (contentLength-readCnt);
|
||||
readLen = in.read(readBuf, 0, (int)readSize);
|
||||
}
|
||||
|
||||
if (isChunkedResponse == true) {
|
||||
out.write("0".getBytes());
|
||||
out.write(HTTP.CRLF.getBytes());
|
||||
}
|
||||
|
||||
out.flush();
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean post(HTTPResponse httpRes, long contentOffset, long contentLength, boolean isOnlyHeader)
|
||||
{
|
||||
if (httpRes.hasContentInputStream() == true)
|
||||
return post(httpRes,httpRes.getContentInputStream(), contentOffset, contentLength, isOnlyHeader);
|
||||
return post(httpRes,httpRes.getContent(), contentOffset, contentLength, isOnlyHeader);
|
||||
}
|
||||
}
|
185
router/java/src/org/cybergarage/http/HTTPStatus.java
Normal file
185
router/java/src/org/cybergarage/http/HTTPStatus.java
Normal file
@ -0,0 +1,185 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: HTTPStatus.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/17/02
|
||||
* - first revision.
|
||||
* 09/03/03
|
||||
* - Added CONTINUE_STATUS.
|
||||
* 10/20/04
|
||||
* - Brent Hills <bhills@openshores.com>
|
||||
* - Added PARTIAL_CONTENT and INVALID_RANGE;
|
||||
* 10/22/04
|
||||
* - Added isSuccessful().
|
||||
* 10/29/04
|
||||
* - Fixed set() to set the version and the response code when the mothod is null.
|
||||
* - Fixed set() to read multi words of the response sring such as Not Found.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class HTTPStatus
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Code
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static final int CONTINUE = 100;
|
||||
public static final int OK = 200;
|
||||
// Thanks for Brent Hills (10/20/04)
|
||||
public static final int PARTIAL_CONTENT = 206;
|
||||
public static final int BAD_REQUEST = 400;
|
||||
public static final int NOT_FOUND = 404;
|
||||
public static final int PRECONDITION_FAILED = 412;
|
||||
// Thanks for Brent Hills (10/20/04)
|
||||
public static final int INVALID_RANGE = 416;
|
||||
public static final int INTERNAL_SERVER_ERROR = 500;
|
||||
|
||||
public static final String code2String(int code)
|
||||
{
|
||||
switch (code) {
|
||||
case CONTINUE: return "Continue";
|
||||
case OK: return "OK";
|
||||
case PARTIAL_CONTENT: return "Partial Content";
|
||||
case BAD_REQUEST: return "Bad Request";
|
||||
case NOT_FOUND: return "Not Found";
|
||||
case PRECONDITION_FAILED: return "Precondition Failed";
|
||||
case INVALID_RANGE: return "Invalid Range";
|
||||
case INTERNAL_SERVER_ERROR: return "Internal Server Error";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPStatus()
|
||||
{
|
||||
setVersion("");
|
||||
setStatusCode(0);
|
||||
setReasonPhrase("");
|
||||
}
|
||||
|
||||
public HTTPStatus(String ver, int code, String reason)
|
||||
{
|
||||
setVersion(ver);
|
||||
setStatusCode(code);
|
||||
setReasonPhrase(reason);
|
||||
}
|
||||
|
||||
public HTTPStatus(String lineStr)
|
||||
{
|
||||
set(lineStr);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String version = "";
|
||||
private int statusCode = 0;
|
||||
private String reasonPhrase = "";
|
||||
|
||||
public void setVersion(String value)
|
||||
{
|
||||
version = value;
|
||||
}
|
||||
|
||||
public void setStatusCode(int value)
|
||||
{
|
||||
statusCode = value;
|
||||
}
|
||||
|
||||
public void setReasonPhrase(String value)
|
||||
{
|
||||
reasonPhrase = value;
|
||||
}
|
||||
|
||||
public String getVersion()
|
||||
{
|
||||
return version;
|
||||
}
|
||||
|
||||
public int getStatusCode()
|
||||
{
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public String getReasonPhrase()
|
||||
{
|
||||
return reasonPhrase;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Status
|
||||
////////////////////////////////////////////////
|
||||
|
||||
final public static boolean isSuccessful(int statCode)
|
||||
{
|
||||
if (200 <= statCode && statCode < 300)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isSuccessful()
|
||||
{
|
||||
return isSuccessful(getStatusCode());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// set
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void set(String lineStr)
|
||||
{
|
||||
if (lineStr == null) {
|
||||
setVersion(HTTP.VERSION);
|
||||
setStatusCode(INTERNAL_SERVER_ERROR);
|
||||
setReasonPhrase(code2String(INTERNAL_SERVER_ERROR));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
StringTokenizer st = new StringTokenizer(lineStr, HTTP.STATUS_LINE_DELIM);
|
||||
|
||||
if (st.hasMoreTokens() == false)
|
||||
return;
|
||||
String ver = st.nextToken();
|
||||
setVersion(ver.trim());
|
||||
|
||||
if (st.hasMoreTokens() == false)
|
||||
return;
|
||||
String codeStr = st.nextToken();
|
||||
int code = 0;
|
||||
try {
|
||||
code = Integer.parseInt(codeStr);
|
||||
}
|
||||
catch (Exception e1) {}
|
||||
setStatusCode(code);
|
||||
|
||||
String reason = "";
|
||||
while (st.hasMoreTokens() == true) {
|
||||
if (0 <= reason.length())
|
||||
reason += " ";
|
||||
reason += st.nextToken();
|
||||
}
|
||||
setReasonPhrase(reason.trim());
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
61
router/java/src/org/cybergarage/http/Parameter.java
Normal file
61
router/java/src/org/cybergarage/http/Parameter.java
Normal file
@ -0,0 +1,61 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: Parameter.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 02/01/04
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
public class Parameter
|
||||
{
|
||||
private String name = new String();
|
||||
private String value = new String();
|
||||
|
||||
public Parameter()
|
||||
{
|
||||
}
|
||||
|
||||
public Parameter(String name, String value)
|
||||
{
|
||||
setName(name);
|
||||
setValue(value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// name
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setName(String name)
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// value
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setValue(String value)
|
||||
{
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getValue()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
60
router/java/src/org/cybergarage/http/ParameterList.java
Normal file
60
router/java/src/org/cybergarage/http/ParameterList.java
Normal file
@ -0,0 +1,60 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: ParameterList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 02/01/04
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.http;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ParameterList extends Vector
|
||||
{
|
||||
private static final long serialVersionUID = -6026765325018137641L;
|
||||
|
||||
public ParameterList()
|
||||
{
|
||||
}
|
||||
|
||||
public Parameter at(int n)
|
||||
{
|
||||
return (Parameter)get(n);
|
||||
}
|
||||
|
||||
public Parameter getParameter(int n)
|
||||
{
|
||||
return (Parameter)get(n);
|
||||
}
|
||||
|
||||
public Parameter getParameter(String name)
|
||||
{
|
||||
if (name == null)
|
||||
return null;
|
||||
|
||||
int nLists = size();
|
||||
for (int n=0; n<nLists; n++) {
|
||||
Parameter param = at(n);
|
||||
if (name.compareTo(param.getName()) == 0)
|
||||
return param;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getValue(String name)
|
||||
{
|
||||
Parameter param = getParameter(name);
|
||||
if (param == null)
|
||||
return "";
|
||||
return param.getValue();
|
||||
}
|
||||
}
|
||||
|
230
router/java/src/org/cybergarage/net/HostInterface.java
Normal file
230
router/java/src/org/cybergarage/net/HostInterface.java
Normal file
@ -0,0 +1,230 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberHTTP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HostInterface.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 05/12/03
|
||||
* - first revision.
|
||||
* 05/13/03
|
||||
* - Added support for IPv6 and loopback address.
|
||||
* 02/15/04
|
||||
* - Added the following methods to set only a interface.
|
||||
* - setInterface(), getInterfaces(), hasAssignedInterface()
|
||||
* 06/30/04
|
||||
* - Moved the package from org.cybergarage.http to org.cybergarage.net.
|
||||
* 06/30/04
|
||||
* - Theo Beisch <theo.beisch@gmx.de>
|
||||
* - Changed isUseAddress() to isUsableAddress().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.net;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
|
||||
public class HostInterface
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean USE_LOOPBACK_ADDR = false;
|
||||
public static boolean USE_ONLY_IPV4_ADDR = false;
|
||||
public static boolean USE_ONLY_IPV6_ADDR = false;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Network Interfaces
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static String ifAddress = "";
|
||||
|
||||
public final static void setInterface(String ifaddr)
|
||||
{
|
||||
ifAddress = ifaddr;
|
||||
}
|
||||
|
||||
public final static String getInterface()
|
||||
{
|
||||
return ifAddress;
|
||||
}
|
||||
|
||||
private final static boolean hasAssignedInterface()
|
||||
{
|
||||
return (0 < ifAddress.length()) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Network Interfaces
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// Thanks for Theo Beisch (10/27/04)
|
||||
|
||||
private final static boolean isUsableAddress(InetAddress addr)
|
||||
{
|
||||
if (USE_LOOPBACK_ADDR == false) {
|
||||
if (addr.isLoopbackAddress() == true)
|
||||
return false;
|
||||
}
|
||||
if (USE_ONLY_IPV4_ADDR == true) {
|
||||
if (addr instanceof Inet6Address)
|
||||
return false;
|
||||
}
|
||||
if (USE_ONLY_IPV6_ADDR == true) {
|
||||
if (addr instanceof Inet4Address)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public final static int getNHostAddresses()
|
||||
{
|
||||
if (hasAssignedInterface() == true)
|
||||
return 1;
|
||||
|
||||
int nHostAddrs = 0;
|
||||
try {
|
||||
Enumeration nis = NetworkInterface.getNetworkInterfaces();
|
||||
while (nis.hasMoreElements()){
|
||||
NetworkInterface ni = (NetworkInterface)nis.nextElement();
|
||||
Enumeration addrs = ni.getInetAddresses();
|
||||
while (addrs.hasMoreElements()) {
|
||||
InetAddress addr = (InetAddress)addrs.nextElement();
|
||||
if (isUsableAddress(addr) == false)
|
||||
continue;
|
||||
nHostAddrs++;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e){};
|
||||
return nHostAddrs;
|
||||
}
|
||||
|
||||
public final static String getHostAddress(int n)
|
||||
{
|
||||
if (hasAssignedInterface() == true)
|
||||
return getInterface();
|
||||
|
||||
int hostAddrCnt = 0;
|
||||
try {
|
||||
Enumeration nis = NetworkInterface.getNetworkInterfaces();
|
||||
while (nis.hasMoreElements()){
|
||||
NetworkInterface ni = (NetworkInterface)nis.nextElement();
|
||||
Enumeration addrs = ni.getInetAddresses();
|
||||
while (addrs.hasMoreElements()) {
|
||||
InetAddress addr = (InetAddress)addrs.nextElement();
|
||||
if (isUsableAddress(addr) == false)
|
||||
continue;
|
||||
if (hostAddrCnt < n) {
|
||||
hostAddrCnt++;
|
||||
continue;
|
||||
}
|
||||
String host = addr.getHostAddress();
|
||||
//if (addr instanceof Inet6Address)
|
||||
// host = "[" + host + "]";
|
||||
return host;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e){};
|
||||
return "";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isIPv?Address
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static boolean isIPv6Address(String host)
|
||||
{
|
||||
try {
|
||||
InetAddress addr = InetAddress.getByName(host);
|
||||
return (addr instanceof Inet6Address);
|
||||
}
|
||||
catch (Exception e) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
public final static boolean isIPv4Address(String host)
|
||||
{
|
||||
try {
|
||||
InetAddress addr = InetAddress.getByName(host);
|
||||
return (addr instanceof Inet4Address);
|
||||
}
|
||||
catch (Exception e) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// hasIPv?Interfaces
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static boolean hasIPv4Addresses()
|
||||
{
|
||||
int addrCnt = getNHostAddresses();
|
||||
for (int n=0; n<addrCnt; n++) {
|
||||
String addr = getHostAddress(n);
|
||||
if (isIPv4Address(addr) == true)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public final static boolean hasIPv6Addresses()
|
||||
{
|
||||
int addrCnt = getNHostAddresses();
|
||||
for (int n=0; n<addrCnt; n++) {
|
||||
String addr = getHostAddress(n);
|
||||
if (isIPv6Address(addr) == true)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// hasIPv?Interfaces
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String getIPv4Address()
|
||||
{
|
||||
int addrCnt = getNHostAddresses();
|
||||
for (int n=0; n<addrCnt; n++) {
|
||||
String addr = getHostAddress(n);
|
||||
if (isIPv4Address(addr) == true)
|
||||
return addr;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public final static String getIPv6Address()
|
||||
{
|
||||
int addrCnt = getNHostAddresses();
|
||||
for (int n=0; n<addrCnt; n++) {
|
||||
String addr = getHostAddress(n);
|
||||
if (isIPv6Address(addr) == true)
|
||||
return addr;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getHostURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String getHostURL(String host, int port, String uri)
|
||||
{
|
||||
String hostAddr = host;
|
||||
if (isIPv6Address(host) == true)
|
||||
hostAddr = "[" + host + "]";
|
||||
return
|
||||
"http://" +
|
||||
hostAddr +
|
||||
":" + Integer.toString(port) +
|
||||
uri;
|
||||
}
|
||||
|
||||
}
|
81
router/java/src/org/cybergarage/soap/SOAP.java
Normal file
81
router/java/src/org/cybergarage/soap/SOAP.java
Normal file
@ -0,0 +1,81 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberSOAP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SOAP.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/11/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.soap;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class SOAP
|
||||
{
|
||||
public static final String ENVELOPE = "Envelope";
|
||||
public static final String BODY = "Body";
|
||||
public static final String RESPONSE = "Response";
|
||||
public static final String FAULT = "Fault";
|
||||
public static final String FAULT_CODE = "faultcode";
|
||||
public static final String FAULT_STRING = "faultstring";
|
||||
public static final String FAULTACTOR = "faultactor";
|
||||
public static final String DETAIL = "detail";
|
||||
|
||||
public static final String RESULTSTATUS = "ResultStatus";
|
||||
public static final String UPNP_ERROR = "UPnPError";
|
||||
public static final String ERROR_CODE = "errorCode";
|
||||
public static final String ERROR_DESCRIPTION = "errorDescription";
|
||||
|
||||
//public static final String XMLNS = "SOAP-ENV";
|
||||
public static final String XMLNS = "s";
|
||||
public static final String METHODNS = "u";
|
||||
public static final String DELIM = ":";
|
||||
|
||||
public static final String XMLNS_URL = "http://schemas.xmlsoap.org/soap/envelope/";
|
||||
public static final String ENCSTYLE_URL = "http://schemas.xmlsoap.org/soap/encoding/";
|
||||
|
||||
public static final String CONTENT_TYPE = "text/xml; charset=\"utf-8\"";
|
||||
public static final String VERSION_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// createEnvelopeBodyNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static Node createEnvelopeBodyNode()
|
||||
{
|
||||
// <Envelope>
|
||||
Node envNode = new Node(SOAP.XMLNS + SOAP.DELIM + SOAP.ENVELOPE);
|
||||
envNode.setAttribute("xmlns" + SOAP.DELIM + SOAP.XMLNS, SOAP.XMLNS_URL);
|
||||
envNode.setAttribute(SOAP.XMLNS + SOAP.DELIM + "encodingStyle", SOAP.ENCSTYLE_URL);
|
||||
|
||||
// <Body>
|
||||
Node bodyNode = new Node(SOAP.XMLNS + SOAP.DELIM + SOAP.BODY);
|
||||
envNode.addNode(bodyNode);
|
||||
|
||||
return envNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// XML Parser
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static Parser xmlParser;
|
||||
|
||||
public final static void setXMLParser(Parser parser)
|
||||
{
|
||||
xmlParser = parser;
|
||||
}
|
||||
|
||||
public final static Parser getXMLParser()
|
||||
{
|
||||
return xmlParser;
|
||||
}
|
||||
}
|
||||
|
183
router/java/src/org/cybergarage/soap/SOAPRequest.java
Normal file
183
router/java/src/org/cybergarage/soap/SOAPRequest.java
Normal file
@ -0,0 +1,183 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberSOAP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SOAPRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/11/02
|
||||
* - first revision.
|
||||
* 02/13/04
|
||||
* - Ralf G. R. Bergs <Ralf@Ber.gs>, Inma Marin Lopez <inma@dif.um.es>.
|
||||
* - Added XML header, <?xml version=\"1.0\"?> to setContent().
|
||||
* 05/11/04
|
||||
* - Changed the XML header to <?xml version="1.0" encoding="utf-8"?> in setContent().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.soap;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class SOAPRequest extends HTTPRequest
|
||||
{
|
||||
private final static String SOAPACTION = "SOAPACTION";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SOAPRequest()
|
||||
{
|
||||
setContentType(SOAP.CONTENT_TYPE);
|
||||
setMethod(HTTP.POST);
|
||||
}
|
||||
|
||||
public SOAPRequest(HTTPRequest httpReq)
|
||||
{
|
||||
set(httpReq);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SOAPACTION
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setSOAPAction(String action)
|
||||
{
|
||||
setStringHeader(SOAPACTION, action);
|
||||
}
|
||||
|
||||
public String getSOAPAction()
|
||||
{
|
||||
return getStringHeaderValue(SOAPACTION);
|
||||
}
|
||||
|
||||
public boolean isSOAPAction(String value)
|
||||
{
|
||||
String headerValue = getHeaderValue(SOAPACTION);
|
||||
if (headerValue == null)
|
||||
return false;
|
||||
if (headerValue.equals(value) == true)
|
||||
return true;
|
||||
String soapAction = getSOAPAction();
|
||||
if (soapAction == null)
|
||||
return false;
|
||||
return soapAction.equals(value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SOAPResponse postMessage(String host, int port)
|
||||
{
|
||||
HTTPResponse httpRes = post(host, port);
|
||||
|
||||
SOAPResponse soapRes = new SOAPResponse(httpRes);
|
||||
|
||||
byte content[] = soapRes.getContent();
|
||||
if (content.length <= 0)
|
||||
return soapRes;
|
||||
|
||||
try {
|
||||
ByteArrayInputStream byteIn = new ByteArrayInputStream(content);
|
||||
Parser xmlParser = SOAP.getXMLParser();
|
||||
Node rootNode = xmlParser.parse(byteIn);
|
||||
soapRes.setEnvelopeNode(rootNode);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
}
|
||||
|
||||
return soapRes;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Node
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node rootNode;
|
||||
|
||||
private void setRootNode(Node node)
|
||||
{
|
||||
rootNode = node;
|
||||
}
|
||||
|
||||
private synchronized Node getRootNode()
|
||||
{
|
||||
if (rootNode != null)
|
||||
return rootNode;
|
||||
|
||||
try {
|
||||
byte content[] = getContent();
|
||||
ByteArrayInputStream contentIn = new ByteArrayInputStream(content);
|
||||
Parser parser = SOAP.getXMLParser();
|
||||
rootNode = parser.parse(contentIn);
|
||||
}
|
||||
catch (ParserException e) {
|
||||
Debug.warning(e);
|
||||
}
|
||||
|
||||
return rootNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// XML
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setEnvelopeNode(Node node)
|
||||
{
|
||||
setRootNode(node);
|
||||
}
|
||||
|
||||
public Node getEnvelopeNode()
|
||||
{
|
||||
return getRootNode();
|
||||
}
|
||||
|
||||
public Node getBodyNode()
|
||||
{
|
||||
Node envNode = getEnvelopeNode();
|
||||
if (envNode == null)
|
||||
return null;
|
||||
if (envNode.hasNodes() == false)
|
||||
return null;
|
||||
return envNode.getNode(0);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// XML Contents
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setContent(Node node)
|
||||
{
|
||||
// Thanks for Ralf G. R. Bergs <Ralf@Ber.gs>, Inma Marin Lopez <inma@dif.um.es>.
|
||||
String conStr = "";
|
||||
conStr += SOAP.VERSION_HEADER;
|
||||
conStr += "\n";
|
||||
conStr += node.toString();
|
||||
setContent(conStr);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// print
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void print()
|
||||
{
|
||||
System.out.println(toString());
|
||||
if (hasContent() == true)
|
||||
return;
|
||||
Node rootElem = getRootNode();
|
||||
if (rootElem == null)
|
||||
return;
|
||||
System.out.println(rootElem.toString());
|
||||
}
|
||||
}
|
191
router/java/src/org/cybergarage/soap/SOAPResponse.java
Normal file
191
router/java/src/org/cybergarage/soap/SOAPResponse.java
Normal file
@ -0,0 +1,191 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberSOAP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SOAPResponse.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/17/02
|
||||
* - first revision.
|
||||
* 02/13/04
|
||||
* - Ralf G. R. Bergs <Ralf@Ber.gs>, Inma Marin Lopez <inma@dif.um.es>.
|
||||
* - Added XML header, <?xml version="1.0"?> to setContent().
|
||||
* 05/11/04
|
||||
* - Changed the XML header to <?xml version="1.0" encoding="utf-8"?> in setContent().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.soap;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class SOAPResponse extends HTTPResponse
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SOAPResponse()
|
||||
{
|
||||
setRootNode(SOAP.createEnvelopeBodyNode());
|
||||
setContentType(XML.CONTENT_TYPE);
|
||||
}
|
||||
|
||||
public SOAPResponse(HTTPResponse httpRes)
|
||||
{
|
||||
super(httpRes);
|
||||
setRootNode(SOAP.createEnvelopeBodyNode());
|
||||
setContentType(XML.CONTENT_TYPE);
|
||||
}
|
||||
|
||||
public SOAPResponse(SOAPResponse soapRes)
|
||||
{
|
||||
super(soapRes);
|
||||
setEnvelopeNode(soapRes.getEnvelopeNode());
|
||||
setContentType(XML.CONTENT_TYPE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Node
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node rootNode;
|
||||
|
||||
private void setRootNode(Node node)
|
||||
{
|
||||
rootNode = node;
|
||||
}
|
||||
|
||||
private Node getRootNode()
|
||||
{
|
||||
return rootNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SOAP Basic
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setEnvelopeNode(Node node)
|
||||
{
|
||||
setRootNode(node);
|
||||
}
|
||||
|
||||
public Node getEnvelopeNode()
|
||||
{
|
||||
return getRootNode();
|
||||
}
|
||||
|
||||
public Node getBodyNode()
|
||||
{
|
||||
Node envNode = getEnvelopeNode();
|
||||
if (envNode == null)
|
||||
return null;
|
||||
return envNode.getNodeEndsWith(SOAP.BODY);
|
||||
}
|
||||
|
||||
public Node getMethodResponseNode(String name)
|
||||
{
|
||||
Node bodyNode = getBodyNode();
|
||||
if (bodyNode == null)
|
||||
return null;
|
||||
String methodResName = name + SOAP.RESPONSE;
|
||||
return bodyNode.getNodeEndsWith(methodResName);
|
||||
}
|
||||
|
||||
public Node getFaultNode()
|
||||
{
|
||||
Node bodyNode = getBodyNode();
|
||||
if (bodyNode == null)
|
||||
return null;
|
||||
return bodyNode.getNodeEndsWith(SOAP.FAULT);
|
||||
}
|
||||
|
||||
public Node getFaultCodeNode()
|
||||
{
|
||||
Node faultNode = getFaultNode();
|
||||
if (faultNode == null)
|
||||
return null;
|
||||
return faultNode.getNodeEndsWith(SOAP.FAULT_CODE);
|
||||
}
|
||||
|
||||
public Node getFaultStringNode()
|
||||
{
|
||||
Node faultNode = getFaultNode();
|
||||
if (faultNode == null)
|
||||
return null;
|
||||
return faultNode.getNodeEndsWith(SOAP.FAULT_STRING);
|
||||
}
|
||||
|
||||
public Node getFaultActorNode()
|
||||
{
|
||||
Node faultNode = getFaultNode();
|
||||
if (faultNode == null)
|
||||
return null;
|
||||
return faultNode.getNodeEndsWith(SOAP.FAULTACTOR);
|
||||
}
|
||||
|
||||
public Node getFaultDetailNode()
|
||||
{
|
||||
Node faultNode = getFaultNode();
|
||||
if (faultNode == null)
|
||||
return null;
|
||||
return faultNode.getNodeEndsWith(SOAP.DETAIL);
|
||||
}
|
||||
|
||||
public String getFaultCode()
|
||||
{
|
||||
Node node = getFaultCodeNode();
|
||||
if (node == null)
|
||||
return "";
|
||||
return node.getValue();
|
||||
}
|
||||
|
||||
public String getFaultString()
|
||||
{
|
||||
Node node = getFaultStringNode();
|
||||
if (node == null)
|
||||
return "";
|
||||
return node.getValue();
|
||||
}
|
||||
|
||||
public String getFaultActor()
|
||||
{
|
||||
Node node = getFaultActorNode();
|
||||
if (node == null)
|
||||
return "";
|
||||
return node.getValue();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// XML Contents
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setContent(Node node)
|
||||
{
|
||||
// Thanks for Ralf G. R. Bergs <Ralf@Ber.gs>, Inma Marin Lopez <inma@dif.um.es>.
|
||||
String conStr = "";
|
||||
conStr += SOAP.VERSION_HEADER;
|
||||
conStr += "\n";
|
||||
conStr += node.toString();
|
||||
setContent(conStr);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// print
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void print()
|
||||
{
|
||||
System.out.println(toString());
|
||||
if (hasContent() == true)
|
||||
return;
|
||||
Node rootElem = getRootNode();
|
||||
if (rootElem == null)
|
||||
return;
|
||||
System.out.println(rootElem.toString());
|
||||
}
|
||||
}
|
370
router/java/src/org/cybergarage/upnp/Action.java
Normal file
370
router/java/src/org/cybergarage/upnp/Action.java
Normal file
@ -0,0 +1,370 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: Action.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/05/02
|
||||
* - first revision.
|
||||
* 08/30/03
|
||||
* - Gordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : When invoking an action that has at least one out parameter, an error message is returned
|
||||
* - Error : The action post method gets the entire list of arguments instead of only the in arguments
|
||||
* 01/04/04
|
||||
* - Added UPnP status methods.
|
||||
* - Changed about new ActionListener interface.
|
||||
* 01/05/04
|
||||
* - Added clearOutputAgumentValues() to initialize the output values before calling performActionListener().
|
||||
* 07/09/04
|
||||
* - Thanks for Dimas <cyberrate@users.sourceforge.net> and Stefano Lenzi <kismet-sl@users.sourceforge.net>
|
||||
* - Changed postControlAction() to set the status code to the UPnPStatus.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
import org.cybergarage.upnp.xml.*;
|
||||
import org.cybergarage.upnp.control.*;
|
||||
|
||||
public class Action
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "action";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node serviceNode;
|
||||
private Node actionNode;
|
||||
|
||||
private Node getServiceNode()
|
||||
{
|
||||
return serviceNode;
|
||||
}
|
||||
|
||||
public Service getService()
|
||||
{
|
||||
return new Service(getServiceNode());
|
||||
}
|
||||
|
||||
public Node getActionNode()
|
||||
{
|
||||
return actionNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Action(Node serviceNode, Node actionNode)
|
||||
{
|
||||
this.serviceNode = serviceNode;
|
||||
this.actionNode = actionNode;
|
||||
}
|
||||
|
||||
public Action(Action action)
|
||||
{
|
||||
this.serviceNode = action.getServiceNode();
|
||||
this.actionNode = action.getActionNode();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Mutex
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Mutex mutex = new Mutex();
|
||||
|
||||
public void lock()
|
||||
{
|
||||
mutex.lock();
|
||||
}
|
||||
|
||||
public void unlock()
|
||||
{
|
||||
mutex.unlock();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isActionNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isActionNode(Node node)
|
||||
{
|
||||
return Action.ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// name
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String NAME = "name";
|
||||
|
||||
public void setName(String value)
|
||||
{
|
||||
getActionNode().setNode(NAME, value);
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return getActionNode().getNodeValue(NAME);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// argumentList
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ArgumentList getArgumentList()
|
||||
{
|
||||
ArgumentList argumentList = new ArgumentList();
|
||||
Node argumentListNode = getActionNode().getNode(ArgumentList.ELEM_NAME);
|
||||
if (argumentListNode == null)
|
||||
return argumentList;
|
||||
int nodeCnt = argumentListNode.getNNodes();
|
||||
for (int n=0; n<nodeCnt; n++) {
|
||||
Node node = argumentListNode.getNode(n);
|
||||
if (Argument.isArgumentNode(node) == false)
|
||||
continue;
|
||||
Argument argument = new Argument(getServiceNode(), node);
|
||||
argumentList.add(argument);
|
||||
}
|
||||
return argumentList;
|
||||
}
|
||||
|
||||
public ArgumentList getInputArgumentList()
|
||||
{
|
||||
ArgumentList allArgList = getArgumentList();
|
||||
int allArgCnt = allArgList.size();
|
||||
ArgumentList argList = new ArgumentList();
|
||||
for (int n=0; n<allArgCnt; n++) {
|
||||
Argument arg = allArgList.getArgument(n);
|
||||
if (arg.isInDirection() == false)
|
||||
continue;
|
||||
argList.add(arg);
|
||||
}
|
||||
return argList;
|
||||
}
|
||||
|
||||
public ArgumentList getOutputArgumentList()
|
||||
{
|
||||
ArgumentList allArgList = getArgumentList();
|
||||
int allArgCnt = allArgList.size();
|
||||
ArgumentList argList = new ArgumentList();
|
||||
for (int n=0; n<allArgCnt; n++) {
|
||||
Argument arg = allArgList.getArgument(n);
|
||||
if (arg.isOutDirection() == false)
|
||||
continue;
|
||||
argList.add(arg);
|
||||
}
|
||||
return argList;
|
||||
}
|
||||
|
||||
public Argument getArgument(String name)
|
||||
{
|
||||
ArgumentList argList = getArgumentList();
|
||||
int nArgs = argList.size();
|
||||
for (int n=0; n<nArgs; n++) {
|
||||
Argument arg = argList.getArgument(n);
|
||||
String argName = arg.getName();
|
||||
if (argName == null)
|
||||
continue;
|
||||
if (name.equals(argName) == true)
|
||||
return arg;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setArgumentValues(ArgumentList argList)
|
||||
{
|
||||
getArgumentList().set(argList);
|
||||
}
|
||||
|
||||
public void setArgumentValue(String name, String value)
|
||||
{
|
||||
Argument arg = getArgument(name);
|
||||
if (arg == null)
|
||||
return;
|
||||
arg.setValue(value);
|
||||
}
|
||||
|
||||
public void setArgumentValue(String name, int value)
|
||||
{
|
||||
setArgumentValue(name, Integer.toString(value));
|
||||
}
|
||||
|
||||
private void clearOutputAgumentValues()
|
||||
{
|
||||
ArgumentList allArgList = getArgumentList();
|
||||
int allArgCnt = allArgList.size();
|
||||
for (int n=0; n<allArgCnt; n++) {
|
||||
Argument arg = allArgList.getArgument(n);
|
||||
if (arg.isOutDirection() == false)
|
||||
continue;
|
||||
arg.setValue("");
|
||||
}
|
||||
}
|
||||
|
||||
public String getArgumentValue(String name)
|
||||
{
|
||||
Argument arg = getArgument(name);
|
||||
if (arg == null)
|
||||
return "";
|
||||
return arg.getValue();
|
||||
}
|
||||
|
||||
public int getArgumentIntegerValue(String name)
|
||||
{
|
||||
Argument arg = getArgument(name);
|
||||
if (arg == null)
|
||||
return 0;
|
||||
return arg.getIntegerValue();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UserData
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ActionData getActionData()
|
||||
{
|
||||
Node node = getActionNode();
|
||||
ActionData userData = (ActionData)node.getUserData();
|
||||
if (userData == null) {
|
||||
userData = new ActionData();
|
||||
node.setUserData(userData);
|
||||
userData.setNode(node);
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// controlAction
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ActionListener getActionListener()
|
||||
{
|
||||
return getActionData().getActionListener();
|
||||
}
|
||||
|
||||
public void setActionListener(ActionListener listener)
|
||||
{
|
||||
getActionData().setActionListener(listener);
|
||||
}
|
||||
|
||||
public boolean performActionListener(ActionRequest actionReq)
|
||||
{
|
||||
ActionListener listener = (ActionListener)getActionListener();
|
||||
if (listener == null)
|
||||
return false;
|
||||
ActionResponse actionRes = new ActionResponse();
|
||||
setStatus(UPnPStatus.INVALID_ACTION);
|
||||
clearOutputAgumentValues();
|
||||
if (listener.actionControlReceived(this) == true) {
|
||||
actionRes.setResponse(this);
|
||||
}
|
||||
else {
|
||||
UPnPStatus upnpStatus = getStatus();
|
||||
actionRes.setFaultResponse(upnpStatus.getCode(), upnpStatus.getDescription());
|
||||
}
|
||||
if (Debug.isOn() == true)
|
||||
actionRes.print();
|
||||
actionReq.post(actionRes);
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ActionControl
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ControlResponse getControlResponse()
|
||||
{
|
||||
return getActionData().getControlResponse();
|
||||
}
|
||||
|
||||
private void setControlResponse(ControlResponse res)
|
||||
{
|
||||
getActionData().setControlResponse(res);
|
||||
}
|
||||
|
||||
public UPnPStatus getControlStatus()
|
||||
{
|
||||
return getControlResponse().getUPnPError();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// postControlAction
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean postControlAction()
|
||||
{
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (08/30/03)
|
||||
ArgumentList actionArgList = getArgumentList();
|
||||
ArgumentList actionInputArgList = getInputArgumentList();
|
||||
ActionRequest ctrlReq = new ActionRequest();
|
||||
ctrlReq.setRequest(this, actionInputArgList);
|
||||
if (Debug.isOn() == true)
|
||||
ctrlReq.print();
|
||||
ActionResponse ctrlRes = ctrlReq.post();
|
||||
if (Debug.isOn() == true)
|
||||
ctrlRes.print();
|
||||
setControlResponse(ctrlRes);
|
||||
// Thanks for Dimas <cyberrate@users.sourceforge.net> and Stefano Lenzi <kismet-sl@users.sourceforge.net> (07/09/04)
|
||||
int statCode = ctrlRes.getStatusCode();
|
||||
setStatus(statCode);
|
||||
if (ctrlRes.isSuccessful() == false)
|
||||
return false;
|
||||
ArgumentList outArgList = ctrlRes.getResponse();
|
||||
actionArgList.set(outArgList);
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Debug
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void print()
|
||||
{
|
||||
System.out.println("Action : " + getName());
|
||||
ArgumentList argList = getArgumentList();
|
||||
int nArgs = argList.size();
|
||||
for (int n=0; n<nArgs; n++) {
|
||||
Argument arg = argList.getArgument(n);
|
||||
String name = arg.getName();
|
||||
String value = arg.getValue();
|
||||
String dir = arg.getDirection();
|
||||
System.out.println(" [" + n + "] = " + dir + ", " + name + ", " + value);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UPnPStatus
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private UPnPStatus upnpStatus = new UPnPStatus();
|
||||
|
||||
public void setStatus(int code, String descr)
|
||||
{
|
||||
upnpStatus.setCode(code);
|
||||
upnpStatus.setDescription(descr);
|
||||
}
|
||||
|
||||
public void setStatus(int code)
|
||||
{
|
||||
setStatus(code, UPnPStatus.code2String(code));
|
||||
}
|
||||
|
||||
public UPnPStatus getStatus()
|
||||
{
|
||||
return upnpStatus;
|
||||
}
|
||||
|
||||
}
|
46
router/java/src/org/cybergarage/upnp/ActionList.java
Normal file
46
router/java/src/org/cybergarage/upnp/ActionList.java
Normal file
@ -0,0 +1,46 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ActionList.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 12/05/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ActionList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 1965922721316119846L;
|
||||
public final static String ELEM_NAME = "actionList";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ActionList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Action getAction(int n)
|
||||
{
|
||||
return (Action)get(n);
|
||||
}
|
||||
}
|
||||
|
70
router/java/src/org/cybergarage/upnp/AllowedValue.java
Normal file
70
router/java/src/org/cybergarage/upnp/AllowedValue.java
Normal file
@ -0,0 +1,70 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: AllowedValue.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 03/27/04
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class AllowedValue
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "allowedValue";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node allowedValueNode;
|
||||
|
||||
public Node getAllowedValueNode()
|
||||
{
|
||||
return allowedValueNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public AllowedValue(Node node)
|
||||
{
|
||||
allowedValueNode = node;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isAllowedValueNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isAllowedValueNode(Node node)
|
||||
{
|
||||
return ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Value
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setValue(String value)
|
||||
{
|
||||
getAllowedValueNode().setValue(value);
|
||||
}
|
||||
|
||||
public String getValue()
|
||||
{
|
||||
return getAllowedValueNode().getValue();
|
||||
}
|
||||
}
|
49
router/java/src/org/cybergarage/upnp/AllowedValueList.java
Normal file
49
router/java/src/org/cybergarage/upnp/AllowedValueList.java
Normal file
@ -0,0 +1,49 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: AllowedValueList.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 03/27/04
|
||||
* - first revision.
|
||||
* 02/28/05
|
||||
* - Changed to use AllowedValue instead of String as the member.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class AllowedValueList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 5740394642751180992L;
|
||||
public final static String ELEM_NAME = "allowedValueList";
|
||||
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public AllowedValueList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public AllowedValue getAllowedValue(int n)
|
||||
{
|
||||
return (AllowedValue)get(n);
|
||||
}
|
||||
|
||||
}
|
104
router/java/src/org/cybergarage/upnp/AllowedValueRange.java
Normal file
104
router/java/src/org/cybergarage/upnp/AllowedValueRange.java
Normal file
@ -0,0 +1,104 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: AllowedValueRange.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 03/27/04
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class AllowedValueRange
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "allowedValueRange";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node allowedValueRangeNode;
|
||||
|
||||
public Node getAllowedValueRangeNode()
|
||||
{
|
||||
return allowedValueRangeNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public AllowedValueRange(Node node)
|
||||
{
|
||||
allowedValueRangeNode = node;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isAllowedValueRangeNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isAllowedValueRangeNode(Node node)
|
||||
{
|
||||
return ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// minimum
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String MINIMUM = "minimum";
|
||||
|
||||
public void setMinimum(String value)
|
||||
{
|
||||
getAllowedValueRangeNode().setNode(MINIMUM, value);
|
||||
}
|
||||
|
||||
public String getMinimum()
|
||||
{
|
||||
return getAllowedValueRangeNode().getNodeValue(MINIMUM);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// maximum
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String MAXIMUM = "maximum";
|
||||
|
||||
public void setMaximum(String value)
|
||||
{
|
||||
getAllowedValueRangeNode().setNode(MAXIMUM, value);
|
||||
}
|
||||
|
||||
public String getMaximum()
|
||||
{
|
||||
return getAllowedValueRangeNode().getNodeValue(MAXIMUM);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// width
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String STEP = "step";
|
||||
|
||||
public void setStep(String value)
|
||||
{
|
||||
getAllowedValueRangeNode().setNode(STEP, value);
|
||||
}
|
||||
|
||||
public String getStep()
|
||||
{
|
||||
return getAllowedValueRangeNode().getNodeValue(STEP);
|
||||
}
|
||||
}
|
231
router/java/src/org/cybergarage/upnp/Argument.java
Normal file
231
router/java/src/org/cybergarage/upnp/Argument.java
Normal file
@ -0,0 +1,231 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: Argument.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/05/02
|
||||
* - first revision.
|
||||
* 03/28/04
|
||||
* - Added getRelatedStateVariable().
|
||||
* - Changed setRelatedStateVariable() to setRelatedStateVariableName().
|
||||
* - Changed getRelatedStateVariable() to getRelatedStateVariableName().
|
||||
* - Added getActionNode() and getAction().
|
||||
* - Added getServiceNode() and getService().
|
||||
* - Added the parent service node to the constructor.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
import org.cybergarage.upnp.xml.*;
|
||||
|
||||
public class Argument
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "argument";
|
||||
|
||||
public final static String IN = "in";
|
||||
public final static String OUT = "out";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node argumentNode;
|
||||
private Node serviceNode;
|
||||
|
||||
public Node getArgumentNode()
|
||||
{
|
||||
return argumentNode;
|
||||
}
|
||||
|
||||
private Node getServiceNode()
|
||||
{
|
||||
return serviceNode;
|
||||
}
|
||||
|
||||
public Service getService()
|
||||
{
|
||||
return new Service(getServiceNode());
|
||||
}
|
||||
|
||||
public Node getActionNode()
|
||||
{
|
||||
Node argumentLinstNode = getArgumentNode().getParentNode();
|
||||
if (argumentLinstNode == null)
|
||||
return null;
|
||||
Node actionNode = argumentLinstNode.getParentNode();
|
||||
if (actionNode == null)
|
||||
return null;
|
||||
if (Action.isActionNode(actionNode) == false)
|
||||
return null;
|
||||
return actionNode;
|
||||
}
|
||||
|
||||
public Action getAction()
|
||||
{
|
||||
return new Action(getServiceNode(), getActionNode());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Argument()
|
||||
{
|
||||
argumentNode = new Node();
|
||||
serviceNode = null;
|
||||
}
|
||||
|
||||
public Argument(Node servNode, Node argNode)
|
||||
{
|
||||
serviceNode = servNode;
|
||||
argumentNode = argNode;
|
||||
}
|
||||
|
||||
public Argument(String name, String value)
|
||||
{
|
||||
this();
|
||||
setName(name);
|
||||
setValue(value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isArgumentNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isArgumentNode(Node node)
|
||||
{
|
||||
return Argument.ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// name
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String NAME = "name";
|
||||
|
||||
public void setName(String value)
|
||||
{
|
||||
getArgumentNode().setNode(NAME, value);
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return getArgumentNode().getNodeValue(NAME);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// direction
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String DIRECTION = "direction";
|
||||
|
||||
public void setDirection(String value)
|
||||
{
|
||||
getArgumentNode().setNode(DIRECTION, value);
|
||||
}
|
||||
|
||||
public String getDirection()
|
||||
{
|
||||
return getArgumentNode().getNodeValue(DIRECTION);
|
||||
}
|
||||
|
||||
public boolean isInDirection()
|
||||
{
|
||||
String dir = getDirection();
|
||||
if (dir == null)
|
||||
return false;
|
||||
return dir.equalsIgnoreCase(IN);
|
||||
}
|
||||
|
||||
public boolean isOutDirection()
|
||||
{
|
||||
return !isInDirection();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// relatedStateVariable
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String RELATED_STATE_VARIABLE = "relatedStateVariable";
|
||||
|
||||
public void setRelatedStateVariableName(String value)
|
||||
{
|
||||
getArgumentNode().setNode(RELATED_STATE_VARIABLE, value);
|
||||
}
|
||||
|
||||
public String getRelatedStateVariableName()
|
||||
{
|
||||
return getArgumentNode().getNodeValue(RELATED_STATE_VARIABLE);
|
||||
}
|
||||
|
||||
public StateVariable getRelatedStateVariable()
|
||||
{
|
||||
Service service = getService();
|
||||
if (service == null)
|
||||
return null;
|
||||
String relatedStatVarName = getRelatedStateVariableName();
|
||||
return service.getStateVariable(relatedStatVarName);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UserData
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ArgumentData getArgumentData()
|
||||
{
|
||||
Node node = getArgumentNode();
|
||||
ArgumentData userData = (ArgumentData)node.getUserData();
|
||||
if (userData == null) {
|
||||
userData = new ArgumentData();
|
||||
node.setUserData(userData);
|
||||
userData.setNode(node);
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// value
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setValue(String value)
|
||||
{
|
||||
getArgumentData().setValue(value);
|
||||
}
|
||||
|
||||
public void setValue(int value)
|
||||
{
|
||||
setValue(Integer.toString(value));
|
||||
}
|
||||
|
||||
public String getValue()
|
||||
{
|
||||
return getArgumentData().getValue();
|
||||
}
|
||||
|
||||
public int getIntegerValue()
|
||||
{
|
||||
String value = getValue();
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
}
|
||||
catch (Exception e) {
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Related
|
||||
////////////////////////////////////////////////
|
||||
}
|
77
router/java/src/org/cybergarage/upnp/ArgumentList.java
Normal file
77
router/java/src/org/cybergarage/upnp/ArgumentList.java
Normal file
@ -0,0 +1,77 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ArgumentList.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 12/05/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ArgumentList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = -5412792105767389170L;
|
||||
public final static String ELEM_NAME = "argumentList";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ArgumentList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Argument getArgument(int n)
|
||||
{
|
||||
return (Argument)get(n);
|
||||
}
|
||||
|
||||
public Argument getArgument(String name)
|
||||
{
|
||||
int nArgs = size();
|
||||
for (int n=0; n<nArgs; n++) {
|
||||
Argument arg = getArgument(n);
|
||||
String argName = arg.getName();
|
||||
if (argName == null)
|
||||
continue;
|
||||
if (argName.equals(name) == true)
|
||||
return arg;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void set(ArgumentList inArgList)
|
||||
{
|
||||
int nInArgs = inArgList.size();
|
||||
for (int n=0; n<nInArgs; n++) {
|
||||
Argument inArg = inArgList.getArgument(n);
|
||||
String inArgName = inArg.getName();
|
||||
Argument arg = getArgument(inArgName);
|
||||
if (arg == null)
|
||||
continue;
|
||||
arg.setValue(inArg.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
917
router/java/src/org/cybergarage/upnp/ControlPoint.java
Normal file
917
router/java/src/org/cybergarage/upnp/ControlPoint.java
Normal file
@ -0,0 +1,917 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: ControlPoint.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 05/13/03
|
||||
* - Changed to create socket threads each local interfaces.
|
||||
* (HTTP, SSDPNotiry, SSDPSerachResponse)
|
||||
* 05/28/03
|
||||
* - Changed to send m-serach packets from SSDPSearchResponseSocket.
|
||||
* The socket doesn't bind interface address.
|
||||
* - SSDPSearchResponsSocketList that binds a port and a interface can't
|
||||
* send m-serch packets of IPv6 on J2SE v 1.4.1_02 and Redhat 9.
|
||||
* 07/23/03
|
||||
* - Suzan Foster (suislief)
|
||||
* - Fixed a bug. HOST field was missing.
|
||||
* 07/29/03
|
||||
* - Synchronized when a device is added by the ssdp message.
|
||||
* 09/08/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : when an event notification message is received and the message
|
||||
* contains updates on more than one variable, only the first variable update
|
||||
* is notified.
|
||||
* - Error : the other xml nodes of the message are ignored
|
||||
* - Fix : add two methods to the NotifyRequest for extracting the property array
|
||||
* and modify the httpRequestRecieved method in ControlPoint
|
||||
* 12/12/03
|
||||
* - Added a static() to initialize UPnP class.
|
||||
* 01/06/04
|
||||
* - Added the following methods to remove expired devices automatically
|
||||
* removeExpiredDevices()
|
||||
* setExpiredDeviceMonitoringInterval()/getExpiredDeviceMonitoringInterval()
|
||||
* setDeviceDisposer()/getDeviceDisposer()
|
||||
* 04/20/04
|
||||
* - Added the following methods.
|
||||
* start(String target, int mx) and start(String target).
|
||||
* 06/23/04
|
||||
* - Added setNMPRMode() and isNMPRMode().
|
||||
* 07/08/04
|
||||
* - Added renewSubscriberService().
|
||||
* - Changed start() to create renew subscriber thread when the NMPR mode is true.
|
||||
* 08/17/04
|
||||
* - Fixed removeExpiredDevices() to remove using the device array.
|
||||
* 10/16/04
|
||||
* - Oliver Newell <newell@media-rush.com>
|
||||
* - Added this class to allow ControlPoint applications to be notified when
|
||||
* the ControlPoint base class adds/removes a UPnP device
|
||||
* 03/30/05
|
||||
* - Changed addDevice() to use Parser::parse(URL).
|
||||
*
|
||||
*******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.net.*;
|
||||
import org.cybergarage.util.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.http.*;
|
||||
|
||||
import org.cybergarage.upnp.control.*;
|
||||
import org.cybergarage.upnp.ssdp.*;
|
||||
import org.cybergarage.upnp.device.*;
|
||||
import org.cybergarage.upnp.event.*;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
public class ControlPoint implements HTTPRequestListener
|
||||
{
|
||||
private final static int DEFAULT_EVENTSUB_PORT = 8058;
|
||||
private final static int DEFAULT_SSDP_PORT = 8008;
|
||||
private final static int DEFAULT_EXPIRED_DEVICE_MONITORING_INTERVAL = 60;
|
||||
|
||||
private final static String DEFAULT_EVENTSUB_URI = "/evetSub";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private SSDPNotifySocketList ssdpNotifySocketList;
|
||||
private SSDPSearchResponseSocketList ssdpSearchResponseSocketList;
|
||||
|
||||
private SSDPNotifySocketList getSSDPNotifySocketList()
|
||||
{
|
||||
return ssdpNotifySocketList;
|
||||
}
|
||||
|
||||
private SSDPSearchResponseSocketList getSSDPSearchResponseSocketList()
|
||||
{
|
||||
return ssdpSearchResponseSocketList;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Initialize
|
||||
////////////////////////////////////////////////
|
||||
|
||||
static
|
||||
{
|
||||
UPnP.initialize();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ControlPoint(int ssdpPort, int httpPort)
|
||||
{
|
||||
ssdpNotifySocketList = new SSDPNotifySocketList();
|
||||
ssdpSearchResponseSocketList = new SSDPSearchResponseSocketList();
|
||||
|
||||
setSSDPPort(ssdpPort);
|
||||
setHTTPPort(httpPort);
|
||||
|
||||
setDeviceDisposer(null);
|
||||
setExpiredDeviceMonitoringInterval(DEFAULT_EXPIRED_DEVICE_MONITORING_INTERVAL);
|
||||
|
||||
setRenewSubscriber(null);
|
||||
|
||||
setNMPRMode(false);
|
||||
setRenewSubscriber(null);
|
||||
}
|
||||
|
||||
public ControlPoint()
|
||||
{
|
||||
this(DEFAULT_SSDP_PORT, DEFAULT_EVENTSUB_PORT);
|
||||
}
|
||||
|
||||
public void finalize()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Mutex
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Mutex mutex = new Mutex();
|
||||
|
||||
public void lock()
|
||||
{
|
||||
mutex.lock();
|
||||
}
|
||||
|
||||
public void unlock()
|
||||
{
|
||||
mutex.unlock();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Port (SSDP)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private int ssdpPort = 0;
|
||||
|
||||
public int getSSDPPort() {
|
||||
return ssdpPort;
|
||||
}
|
||||
|
||||
public void setSSDPPort(int port) {
|
||||
ssdpPort = port;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Port (EventSub)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private int httpPort = 0;
|
||||
|
||||
public int getHTTPPort() {
|
||||
return httpPort;
|
||||
}
|
||||
|
||||
public void setHTTPPort(int port) {
|
||||
httpPort = port;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// NMPR
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private boolean nmprMode;
|
||||
|
||||
public void setNMPRMode(boolean flag)
|
||||
{
|
||||
nmprMode = flag;
|
||||
}
|
||||
|
||||
public boolean isNMPRMode()
|
||||
{
|
||||
return nmprMode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Device List
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private NodeList devNodeList = new NodeList();
|
||||
|
||||
private void addDevice(Node rootNode)
|
||||
{
|
||||
devNodeList.add(rootNode);
|
||||
}
|
||||
|
||||
private synchronized void addDevice(SSDPPacket ssdpPacket)
|
||||
{
|
||||
if (ssdpPacket.isRootDevice() == false)
|
||||
return;
|
||||
|
||||
String usn = ssdpPacket.getUSN();
|
||||
String udn = USN.getUDN(usn);
|
||||
Device dev = getDevice(udn);
|
||||
if (dev != null) {
|
||||
dev.setSSDPPacket(ssdpPacket);
|
||||
return;
|
||||
}
|
||||
|
||||
String location = ssdpPacket.getLocation();
|
||||
try {
|
||||
URL locationUrl = new URL(location);
|
||||
Parser parser = UPnP.getXMLParser();
|
||||
Node rootNode = parser.parse(locationUrl);
|
||||
Device rootDev = getDevice(rootNode);
|
||||
if (rootDev == null)
|
||||
return;
|
||||
rootDev.setSSDPPacket(ssdpPacket);
|
||||
addDevice(rootNode);
|
||||
|
||||
// Thanks for Oliver Newell (2004/10/16)
|
||||
// After node is added, invoke the AddDeviceListener to notify high-level
|
||||
// control point application that a new device has been added. (The
|
||||
// control point application must implement the DeviceChangeListener interface
|
||||
// to receive the notifications)
|
||||
performAddDeviceListener( rootDev );
|
||||
}
|
||||
catch (MalformedURLException me) {
|
||||
Debug.warning(ssdpPacket.toString());
|
||||
Debug.warning(me);
|
||||
}
|
||||
catch (ParserException pe) {
|
||||
Debug.warning(ssdpPacket.toString());
|
||||
Debug.warning(pe);
|
||||
}
|
||||
}
|
||||
|
||||
private Device getDevice(Node rootNode)
|
||||
{
|
||||
if (rootNode == null)
|
||||
return null;
|
||||
Node devNode = rootNode.getNode(Device.ELEM_NAME);
|
||||
if (devNode == null)
|
||||
return null;
|
||||
return new Device(rootNode, devNode);
|
||||
}
|
||||
|
||||
public DeviceList getDeviceList()
|
||||
{
|
||||
DeviceList devList = new DeviceList();
|
||||
int nRoots = devNodeList.size();
|
||||
for (int n=0; n<nRoots; n++) {
|
||||
Node rootNode = devNodeList.getNode(n);
|
||||
Device dev = getDevice(rootNode);
|
||||
if (dev == null)
|
||||
continue;
|
||||
devList.add(dev);
|
||||
}
|
||||
return devList;
|
||||
}
|
||||
|
||||
public Device getDevice(String name)
|
||||
{
|
||||
int nRoots = devNodeList.size();
|
||||
for (int n=0; n<nRoots; n++) {
|
||||
Node rootNode = devNodeList.getNode(n);
|
||||
Device dev = getDevice(rootNode);
|
||||
if (dev == null)
|
||||
continue;
|
||||
if (dev.isDevice(name) == true)
|
||||
return dev;
|
||||
Device cdev = dev.getDevice(name);
|
||||
if (cdev != null)
|
||||
return cdev;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean hasDevice(String name)
|
||||
{
|
||||
return (getDevice(name) != null) ? true : false;
|
||||
}
|
||||
|
||||
private void removeDevice(Node rootNode)
|
||||
{
|
||||
// Thanks for Oliver Newell (2004/10/16)
|
||||
// Invoke device removal listener prior to actual removal so Device node
|
||||
// remains valid for the duration of the listener (application may want
|
||||
// to access the node)
|
||||
Device dev = getDevice(rootNode);
|
||||
if( dev != null && dev.isRootDevice() )
|
||||
performRemoveDeviceListener( dev );
|
||||
|
||||
devNodeList.remove(rootNode);
|
||||
}
|
||||
|
||||
private void removeDevice(Device dev)
|
||||
{
|
||||
if (dev == null)
|
||||
return;
|
||||
removeDevice(dev.getRootNode());
|
||||
}
|
||||
|
||||
private void removeDevice(String name)
|
||||
{
|
||||
Device dev = getDevice(name);
|
||||
removeDevice(dev);
|
||||
}
|
||||
|
||||
private void removeDevice(SSDPPacket packet)
|
||||
{
|
||||
if (packet.isByeBye() == false)
|
||||
return;
|
||||
String usn = packet.getUSN();
|
||||
String udn = USN.getUDN(usn);
|
||||
removeDevice(udn);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Expired Device
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Disposer deviceDisposer;
|
||||
private long expiredDeviceMonitoringInterval;
|
||||
|
||||
public void removeExpiredDevices()
|
||||
{
|
||||
DeviceList devList = getDeviceList();
|
||||
int devCnt = devList.size();
|
||||
Device dev[] = new Device[devCnt];
|
||||
for (int n=0; n<devCnt; n++)
|
||||
dev[n] = devList.getDevice(n);
|
||||
for (int n=0; n<devCnt; n++) {
|
||||
if (dev[n].isExpired() == true) {
|
||||
Debug.message("Expired device = " + dev[n].getFriendlyName());
|
||||
removeDevice(dev[n]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setExpiredDeviceMonitoringInterval(long interval)
|
||||
{
|
||||
expiredDeviceMonitoringInterval = interval;
|
||||
}
|
||||
|
||||
public long getExpiredDeviceMonitoringInterval()
|
||||
{
|
||||
return expiredDeviceMonitoringInterval;
|
||||
}
|
||||
|
||||
public void setDeviceDisposer(Disposer disposer)
|
||||
{
|
||||
deviceDisposer = disposer;
|
||||
}
|
||||
|
||||
public Disposer getDeviceDisposer()
|
||||
{
|
||||
return deviceDisposer;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Notify
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ListenerList deviceNotifyListenerList = new ListenerList();
|
||||
|
||||
public void addNotifyListener(NotifyListener listener)
|
||||
{
|
||||
deviceNotifyListenerList.add(listener);
|
||||
}
|
||||
|
||||
public void removeNotifyListener(NotifyListener listener)
|
||||
{
|
||||
deviceNotifyListenerList.remove(listener);
|
||||
}
|
||||
|
||||
public void performNotifyListener(SSDPPacket ssdpPacket)
|
||||
{
|
||||
int listenerSize = deviceNotifyListenerList.size();
|
||||
for (int n=0; n<listenerSize; n++) {
|
||||
NotifyListener listener = (NotifyListener)deviceNotifyListenerList.get(n);
|
||||
listener.deviceNotifyReceived(ssdpPacket);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SearchResponse
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ListenerList deviceSearchResponseListenerList = new ListenerList();
|
||||
|
||||
public void addSearchResponseListener(SearchResponseListener listener)
|
||||
{
|
||||
deviceSearchResponseListenerList.add(listener);
|
||||
}
|
||||
|
||||
public void removeSearchResponseListener(SearchResponseListener listener)
|
||||
{
|
||||
deviceSearchResponseListenerList.remove(listener);
|
||||
}
|
||||
|
||||
public void performSearchResponseListener(SSDPPacket ssdpPacket)
|
||||
{
|
||||
int listenerSize = deviceSearchResponseListenerList.size();
|
||||
for (int n=0; n<listenerSize; n++) {
|
||||
SearchResponseListener listener = (SearchResponseListener)deviceSearchResponseListenerList.get(n);
|
||||
listener.deviceSearchResponseReceived(ssdpPacket);
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// Device status changes (device added or removed)
|
||||
// Applications that support the DeviceChangeListener interface are
|
||||
// notified immediately when a device is added to, or removed from,
|
||||
// the control point.
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
ListenerList deviceChangeListenerList = new ListenerList();
|
||||
|
||||
public void addDeviceChangeListener(DeviceChangeListener listener)
|
||||
{
|
||||
deviceChangeListenerList.add(listener);
|
||||
}
|
||||
|
||||
public void removeDeviceChangeListener(DeviceChangeListener listener)
|
||||
{
|
||||
deviceChangeListenerList.remove(listener);
|
||||
}
|
||||
|
||||
public void performAddDeviceListener( Device dev )
|
||||
{
|
||||
int listenerSize = deviceChangeListenerList.size();
|
||||
for (int n=0; n<listenerSize; n++) {
|
||||
DeviceChangeListener listener = (DeviceChangeListener)deviceChangeListenerList.get(n);
|
||||
listener.deviceAdded( dev );
|
||||
}
|
||||
}
|
||||
|
||||
public void performRemoveDeviceListener( Device dev )
|
||||
{
|
||||
int listenerSize = deviceChangeListenerList.size();
|
||||
for (int n=0; n<listenerSize; n++) {
|
||||
DeviceChangeListener listener = (DeviceChangeListener)deviceChangeListenerList.get(n);
|
||||
listener.deviceRemoved( dev );
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SSDPPacket
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void notifyReceived(SSDPPacket packet)
|
||||
{
|
||||
if (packet.isRootDevice() == true) {
|
||||
if (packet.isAlive() == true)
|
||||
addDevice(packet);
|
||||
if (packet.isByeBye() == true)
|
||||
removeDevice(packet);
|
||||
}
|
||||
performNotifyListener(packet);
|
||||
}
|
||||
|
||||
public void searchResponseReceived(SSDPPacket packet)
|
||||
{
|
||||
if (packet.isRootDevice() == true)
|
||||
addDevice(packet);
|
||||
performSearchResponseListener(packet);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// M-SEARCH
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private int searchMx = SSDP.DEFAULT_MSEARCH_MX;
|
||||
|
||||
public int getSearchMx()
|
||||
{
|
||||
return searchMx;
|
||||
}
|
||||
|
||||
public void setSearchMx(int mx)
|
||||
{
|
||||
searchMx = mx;
|
||||
}
|
||||
|
||||
public void search(String target, int mx)
|
||||
{
|
||||
SSDPSearchRequest msReq = new SSDPSearchRequest(target, mx);
|
||||
SSDPSearchResponseSocketList ssdpSearchResponseSocketList = getSSDPSearchResponseSocketList();
|
||||
ssdpSearchResponseSocketList.post(msReq);
|
||||
}
|
||||
|
||||
public void search(String target)
|
||||
{
|
||||
search(target, SSDP.DEFAULT_MSEARCH_MX);
|
||||
}
|
||||
|
||||
public void search()
|
||||
{
|
||||
search(ST.ROOT_DEVICE, SSDP.DEFAULT_MSEARCH_MX);
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// EventSub HTTPServer
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private HTTPServerList httpServerList = new HTTPServerList();
|
||||
|
||||
private HTTPServerList getHTTPServerList()
|
||||
{
|
||||
return httpServerList;
|
||||
}
|
||||
|
||||
public void httpRequestRecieved(HTTPRequest httpReq)
|
||||
{
|
||||
if (Debug.isOn() == true)
|
||||
httpReq.print();
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/08/03)
|
||||
if (httpReq.isNotifyRequest() == true) {
|
||||
NotifyRequest notifyReq = new NotifyRequest(httpReq);
|
||||
String uuid = notifyReq.getSID();
|
||||
long seq = notifyReq.getSEQ();
|
||||
PropertyList props = notifyReq.getPropertyList();
|
||||
int propCnt = props.size();
|
||||
for (int n = 0; n < propCnt; n++) {
|
||||
Property prop = props.getProperty(n);
|
||||
String varName = prop.getName();
|
||||
String varValue = prop.getValue();
|
||||
performEventListener(uuid, seq, varName, varValue);
|
||||
}
|
||||
httpReq.returnOK();
|
||||
return;
|
||||
}
|
||||
|
||||
httpReq.returnBadRequest();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Event Listener
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ListenerList eventListenerList = new ListenerList();
|
||||
|
||||
public void addEventListener(EventListener listener)
|
||||
{
|
||||
eventListenerList.add(listener);
|
||||
}
|
||||
|
||||
public void removeEventListener(EventListener listener)
|
||||
{
|
||||
eventListenerList.remove(listener);
|
||||
}
|
||||
|
||||
public void performEventListener(String uuid, long seq, String name, String value)
|
||||
{
|
||||
int listenerSize = eventListenerList.size();
|
||||
for (int n=0; n<listenerSize; n++) {
|
||||
EventListener listener = (EventListener)eventListenerList.get(n);
|
||||
listener.eventNotifyReceived(uuid, seq, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Subscription
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String eventSubURI = DEFAULT_EVENTSUB_URI;
|
||||
|
||||
public String getEventSubURI()
|
||||
{
|
||||
return eventSubURI;
|
||||
}
|
||||
|
||||
public void setEventSubURI(String url)
|
||||
{
|
||||
eventSubURI = url;
|
||||
}
|
||||
|
||||
private String getEventSubCallbackURL(String host)
|
||||
{
|
||||
return HostInterface.getHostURL(host, getHTTPPort(), getEventSubURI());
|
||||
}
|
||||
|
||||
public boolean subscribe(Service service, long timeout)
|
||||
{
|
||||
if (service.isSubscribed() == true) {
|
||||
String sid = service.getSID();
|
||||
return subscribe(service, sid, timeout);
|
||||
}
|
||||
|
||||
Device rootDev = service.getRootDevice();
|
||||
if (rootDev == null)
|
||||
return false;
|
||||
String ifAddress = rootDev.getInterfaceAddress();
|
||||
SubscriptionRequest subReq = new SubscriptionRequest();
|
||||
subReq.setSubscribeRequest(service, getEventSubCallbackURL(ifAddress), timeout);
|
||||
SubscriptionResponse subRes = subReq.post();
|
||||
if (subRes.isSuccessful() == true) {
|
||||
service.setSID(subRes.getSID());
|
||||
service.setTimeout(subRes.getTimeout());
|
||||
return true;
|
||||
|
||||
}
|
||||
service.clearSID();
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean subscribe(Service service)
|
||||
{
|
||||
return subscribe(service, Subscription.INFINITE_VALUE);
|
||||
}
|
||||
|
||||
public boolean subscribe(Service service, String uuid, long timeout)
|
||||
{
|
||||
SubscriptionRequest subReq = new SubscriptionRequest();
|
||||
subReq.setRenewRequest(service, uuid, timeout);
|
||||
if (Debug.isOn() == true)
|
||||
subReq.print();
|
||||
SubscriptionResponse subRes = subReq.post();
|
||||
if (Debug.isOn() == true)
|
||||
subRes.print();
|
||||
if (subRes.isSuccessful() == true) {
|
||||
service.setSID(subRes.getSID());
|
||||
service.setTimeout(subRes.getTimeout());
|
||||
return true;
|
||||
}
|
||||
service.clearSID();
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean subscribe(Service service, String uuid)
|
||||
{
|
||||
return subscribe(service, uuid, Subscription.INFINITE_VALUE);
|
||||
}
|
||||
|
||||
public boolean isSubscribed(Service service)
|
||||
{
|
||||
if (service == null)
|
||||
return false;
|
||||
return service.isSubscribed();
|
||||
}
|
||||
|
||||
public boolean unsubscribe(Service service)
|
||||
{
|
||||
SubscriptionRequest subReq = new SubscriptionRequest();
|
||||
subReq.setUnsubscribeRequest(service);
|
||||
SubscriptionResponse subRes = subReq.post();
|
||||
if (subRes.isSuccessful() == true) {
|
||||
service.clearSID();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void unsubscribe(Device device)
|
||||
{
|
||||
ServiceList serviceList = device.getServiceList();
|
||||
int serviceCnt = serviceList.size();
|
||||
for (int n=0; n<serviceCnt; n++) {
|
||||
Service service = serviceList.getService(n);
|
||||
if (service.hasSID() == true)
|
||||
unsubscribe(service);
|
||||
}
|
||||
|
||||
DeviceList childDevList = device.getDeviceList();
|
||||
int childDevCnt = childDevList.size();
|
||||
for (int n=0; n<childDevCnt; n++) {
|
||||
Device cdev = childDevList.getDevice(n);
|
||||
unsubscribe(cdev);
|
||||
}
|
||||
}
|
||||
|
||||
public void unsubscribe()
|
||||
{
|
||||
DeviceList devList = getDeviceList();
|
||||
int devCnt = devList.size();
|
||||
for (int n=0; n<devCnt; n++) {
|
||||
Device dev = devList.getDevice(n);
|
||||
unsubscribe(dev);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getSubscriberService
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Service getSubscriberService(String uuid)
|
||||
{
|
||||
DeviceList devList = getDeviceList();
|
||||
int devCnt = devList.size();
|
||||
for (int n=0; n<devCnt; n++) {
|
||||
Device dev = devList.getDevice(n);
|
||||
Service service = dev.getSubscriberService(uuid);
|
||||
if (service != null)
|
||||
return service;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getSubscriberService
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void renewSubscriberService(Device dev, long timeout)
|
||||
{
|
||||
ServiceList serviceList = dev.getServiceList();
|
||||
int serviceCnt = serviceList.size();
|
||||
for (int n=0; n<serviceCnt; n++) {
|
||||
Service service = serviceList.getService(n);
|
||||
if (service.isSubscribed() == false)
|
||||
continue;
|
||||
String sid = service.getSID();
|
||||
boolean isRenewed = subscribe(service, sid, timeout);
|
||||
if (isRenewed == false)
|
||||
subscribe(service, timeout);
|
||||
}
|
||||
|
||||
DeviceList cdevList = dev.getDeviceList();
|
||||
int cdevCnt = cdevList.size();
|
||||
for (int n=0; n<cdevCnt; n++) {
|
||||
Device cdev = cdevList.getDevice(n);
|
||||
renewSubscriberService(cdev, timeout);
|
||||
}
|
||||
}
|
||||
|
||||
public void renewSubscriberService(long timeout)
|
||||
{
|
||||
DeviceList devList = getDeviceList();
|
||||
int devCnt = devList.size();
|
||||
for (int n=0; n<devCnt; n++) {
|
||||
Device dev = devList.getDevice(n);
|
||||
renewSubscriberService(dev, timeout);
|
||||
}
|
||||
}
|
||||
|
||||
public void renewSubscriberService()
|
||||
{
|
||||
renewSubscriberService(Subscription.INFINITE_VALUE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Subscriber
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private RenewSubscriber renewSubscriber;
|
||||
|
||||
public void setRenewSubscriber(RenewSubscriber sub)
|
||||
{
|
||||
renewSubscriber = sub;
|
||||
}
|
||||
|
||||
public RenewSubscriber getRenewSubscriber()
|
||||
{
|
||||
return renewSubscriber;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// run
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean start(String target, int mx)
|
||||
{
|
||||
stop();
|
||||
|
||||
////////////////////////////////////////
|
||||
// HTTP Server
|
||||
////////////////////////////////////////
|
||||
|
||||
int retryCnt = 0;
|
||||
int bindPort = getHTTPPort();
|
||||
HTTPServerList httpServerList = getHTTPServerList();
|
||||
while (httpServerList.open(bindPort) == false) {
|
||||
retryCnt++;
|
||||
if (UPnP.SERVER_RETRY_COUNT < retryCnt)
|
||||
return false;
|
||||
setHTTPPort(bindPort + 1);
|
||||
bindPort = getHTTPPort();
|
||||
}
|
||||
httpServerList.addRequestListener(this);
|
||||
httpServerList.start();
|
||||
|
||||
////////////////////////////////////////
|
||||
// Notify Socket
|
||||
////////////////////////////////////////
|
||||
|
||||
SSDPNotifySocketList ssdpNotifySocketList = getSSDPNotifySocketList();
|
||||
if (ssdpNotifySocketList.open() == false)
|
||||
return false;
|
||||
ssdpNotifySocketList.setControlPoint(this);
|
||||
ssdpNotifySocketList.start();
|
||||
|
||||
////////////////////////////////////////
|
||||
// SeachResponse Socket
|
||||
////////////////////////////////////////
|
||||
|
||||
int ssdpPort = getSSDPPort();
|
||||
retryCnt = 0;
|
||||
SSDPSearchResponseSocketList ssdpSearchResponseSocketList = getSSDPSearchResponseSocketList();
|
||||
while (ssdpSearchResponseSocketList.open(ssdpPort) == false) {
|
||||
retryCnt++;
|
||||
if (UPnP.SERVER_RETRY_COUNT < retryCnt)
|
||||
return false;
|
||||
setSSDPPort(ssdpPort + 1);
|
||||
ssdpPort = getSSDPPort();
|
||||
}
|
||||
ssdpSearchResponseSocketList.setControlPoint(this);
|
||||
ssdpSearchResponseSocketList.start();
|
||||
|
||||
////////////////////////////////////////
|
||||
// search root devices
|
||||
////////////////////////////////////////
|
||||
|
||||
search(target, mx);
|
||||
|
||||
////////////////////////////////////////
|
||||
// Disposer
|
||||
////////////////////////////////////////
|
||||
|
||||
Disposer disposer = new Disposer(this);
|
||||
setDeviceDisposer(disposer);
|
||||
disposer.start();
|
||||
|
||||
////////////////////////////////////////
|
||||
// Subscriber
|
||||
////////////////////////////////////////
|
||||
|
||||
if (isNMPRMode() == true) {
|
||||
RenewSubscriber renewSub = new RenewSubscriber(this);
|
||||
setRenewSubscriber(renewSub);
|
||||
renewSub.start();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean start(String target)
|
||||
{
|
||||
return start(target, SSDP.DEFAULT_MSEARCH_MX);
|
||||
}
|
||||
|
||||
public boolean start()
|
||||
{
|
||||
return start(ST.ROOT_DEVICE, SSDP.DEFAULT_MSEARCH_MX);
|
||||
}
|
||||
|
||||
public boolean stop()
|
||||
{
|
||||
unsubscribe();
|
||||
|
||||
SSDPNotifySocketList ssdpNotifySocketList = getSSDPNotifySocketList();
|
||||
ssdpNotifySocketList.stop();
|
||||
ssdpNotifySocketList.close();
|
||||
ssdpNotifySocketList.clear();
|
||||
|
||||
SSDPSearchResponseSocketList ssdpSearchResponseSocketList = getSSDPSearchResponseSocketList();
|
||||
ssdpSearchResponseSocketList.stop();
|
||||
ssdpSearchResponseSocketList.close();
|
||||
ssdpSearchResponseSocketList.clear();
|
||||
|
||||
HTTPServerList httpServerList = getHTTPServerList();
|
||||
httpServerList.stop();
|
||||
httpServerList.close();
|
||||
httpServerList.clear();
|
||||
|
||||
////////////////////////////////////////
|
||||
// Disposer
|
||||
////////////////////////////////////////
|
||||
|
||||
Disposer disposer = getDeviceDisposer();
|
||||
if (disposer != null) {
|
||||
disposer.stop();
|
||||
setDeviceDisposer(null);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
// Subscriber
|
||||
////////////////////////////////////////
|
||||
|
||||
RenewSubscriber renewSub = getRenewSubscriber();
|
||||
if (renewSub != null) {
|
||||
renewSub.stop();
|
||||
setRenewSubscriber(null);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// print
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void print()
|
||||
{
|
||||
DeviceList devList = getDeviceList();
|
||||
int devCnt = devList.size();
|
||||
Debug.message("Device Num = " + devCnt);
|
||||
for (int n=0; n<devCnt; n++) {
|
||||
Device dev = devList.getDevice(n);
|
||||
Debug.message("[" + n + "] " + dev.getFriendlyName() + ", " + dev.getLeaseTime() + ", " + dev.getElapsedTime());
|
||||
}
|
||||
}
|
||||
}
|
1809
router/java/src/org/cybergarage/upnp/Device.java
Normal file
1809
router/java/src/org/cybergarage/upnp/Device.java
Normal file
File diff suppressed because it is too large
Load Diff
46
router/java/src/org/cybergarage/upnp/DeviceList.java
Normal file
46
router/java/src/org/cybergarage/upnp/DeviceList.java
Normal file
@ -0,0 +1,46 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: DeviceList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/04/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class DeviceList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 3773784061607435126L;
|
||||
public final static String ELEM_NAME = "deviceList";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public DeviceList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Device getDevice(int n)
|
||||
{
|
||||
return (Device)get(n);
|
||||
}
|
||||
}
|
||||
|
136
router/java/src/org/cybergarage/upnp/Icon.java
Normal file
136
router/java/src/org/cybergarage/upnp/Icon.java
Normal file
@ -0,0 +1,136 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: Icon.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/28/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class Icon
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "icon";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node iconNode;
|
||||
|
||||
public Node getIconNode()
|
||||
{
|
||||
return iconNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Icon(Node node)
|
||||
{
|
||||
iconNode = node;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isIconNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isIconNode(Node node)
|
||||
{
|
||||
return Icon.ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// mimeType
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String MIME_TYPE = "mimeType";
|
||||
|
||||
public void setMimeType(String value)
|
||||
{
|
||||
getIconNode().setNode(MIME_TYPE, value);
|
||||
}
|
||||
|
||||
public String getMimeType()
|
||||
{
|
||||
return getIconNode().getNodeValue(MIME_TYPE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// width
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String WIDTH = "width";
|
||||
|
||||
public void setWidth(String value)
|
||||
{
|
||||
getIconNode().setNode(WIDTH, value);
|
||||
}
|
||||
|
||||
public String getWidth()
|
||||
{
|
||||
return getIconNode().getNodeValue(WIDTH);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// height
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String HEIGHT = "height";
|
||||
|
||||
public void setHeight(String value)
|
||||
{
|
||||
getIconNode().setNode(HEIGHT, value);
|
||||
}
|
||||
|
||||
public String getHeight()
|
||||
{
|
||||
return getIconNode().getNodeValue(HEIGHT);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// depth
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String DEPTH = "depth";
|
||||
|
||||
public void setDepth(String value)
|
||||
{
|
||||
getIconNode().setNode(DEPTH, value);
|
||||
}
|
||||
|
||||
public String getDepth()
|
||||
{
|
||||
return getIconNode().getNodeValue(DEPTH);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// URL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String URL = "url";
|
||||
|
||||
public void setURL(String value)
|
||||
{
|
||||
getIconNode().setNode(URL, value);
|
||||
}
|
||||
|
||||
public String getURL()
|
||||
{
|
||||
return getIconNode().getNodeValue(URL);
|
||||
}
|
||||
}
|
46
router/java/src/org/cybergarage/upnp/IconList.java
Normal file
46
router/java/src/org/cybergarage/upnp/IconList.java
Normal file
@ -0,0 +1,46 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: IconList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/04/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class IconList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = -1097238335037012991L;
|
||||
public final static String ELEM_NAME = "iconList";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public IconList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Icon getIcon(int n)
|
||||
{
|
||||
return (Icon)get(n);
|
||||
}
|
||||
}
|
||||
|
747
router/java/src/org/cybergarage/upnp/Service.java
Normal file
747
router/java/src/org/cybergarage/upnp/Service.java
Normal file
@ -0,0 +1,747 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: Service.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/28/02
|
||||
* - first revision.
|
||||
* 04/12/02
|
||||
* - Holmes, Arran C <acholm@essex.ac.uk>
|
||||
* - Fixed SERVICE_ID constant instead of "serviceId".
|
||||
* 06/17/03
|
||||
* - Added notifyAllStateVariables().
|
||||
* 09/03/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : The device does not accepts request for services when control or subscription urls are absolute
|
||||
* - Error : device methods, when requests are received, search for services that have a controlUrl (or eventSubUrl) equal to the request URI
|
||||
* but request URI must be relative, so they cannot equal absolute urls
|
||||
* 09/03/03
|
||||
* - Steven Yen
|
||||
* - description: to retrieve service information based on information in URLBase and SCPDURL
|
||||
* - problem: not able to retrieve service information when URLBase is missing and SCPDURL is relative
|
||||
* - fix: modify to retrieve host information from Header's Location (required) field and update the
|
||||
* BaseURL tag in the xml so subsequent information retrieval can be done (Steven Yen, 8.27.2003)
|
||||
* - note: 1. in the case that Header's Location field combine with SCPDURL is not able to retrieve proper
|
||||
* information, updating BaseURL would not hurt, since exception will be thrown with or without update.
|
||||
* 2. this problem was discovered when using PC running MS win XP with ICS enabled (gateway).
|
||||
* It seems that root device xml file does not have BaseURL and SCPDURL are all relative.
|
||||
* 3. UPnP device architecture states that BaseURL is optional and SCPDURL may be relative as
|
||||
* specified by UPnP vendor, so MS does not seem to violate the rule.
|
||||
* 10/22/03
|
||||
* - Added setActionListener().
|
||||
* 01/04/04
|
||||
* - Changed about new QueryListener interface.
|
||||
* 01/06/04
|
||||
* - Moved the following methods to StateVariable class.
|
||||
* getQueryListener()
|
||||
* setQueryListener()
|
||||
* performQueryListener()
|
||||
* - Added new setQueryListener() to set a listner to all state variables.
|
||||
* 07/02/04
|
||||
* - Added serviceSearchResponse().
|
||||
* - Deleted getLocationURL().
|
||||
* - Fixed announce() to set the root device URL to the LOCATION field.
|
||||
* 07/31/04
|
||||
* - Changed notify() to remove the expired subscribers and not to remove the invalid response subscribers for NMPR.
|
||||
* 10/29/04
|
||||
* - Fixed a bug when notify() removes the expired devices().
|
||||
* 03/23/05
|
||||
* - Added loadSCPD() to load the description from memory.
|
||||
* 03/30/05
|
||||
* - Added isSCPDURL().
|
||||
* - Removed setDescriptionURL() and getDescriptionURL()
|
||||
* 03/31/05
|
||||
* - Added getSCPDData().
|
||||
* 04/25/05
|
||||
* - Thanks for Mikael Hakman <mhakman@dkab.net>
|
||||
* - Changed getSCPDData() to add a XML declaration at first line.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
import org.cybergarage.upnp.ssdp.*;
|
||||
import org.cybergarage.upnp.xml.*;
|
||||
import org.cybergarage.upnp.device.*;
|
||||
import org.cybergarage.upnp.control.*;
|
||||
import org.cybergarage.upnp.event.*;
|
||||
|
||||
public class Service
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "service";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node serviceNode;
|
||||
|
||||
public Node getServiceNode()
|
||||
{
|
||||
return serviceNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Service(Node node)
|
||||
{
|
||||
serviceNode = node;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Mutex
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Mutex mutex = new Mutex();
|
||||
|
||||
public void lock()
|
||||
{
|
||||
mutex.lock();
|
||||
}
|
||||
|
||||
public void unlock()
|
||||
{
|
||||
mutex.unlock();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isServiceNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isServiceNode(Node node)
|
||||
{
|
||||
return Service.ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Device/Root Node
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node getDeviceNode()
|
||||
{
|
||||
Node node = getServiceNode().getParentNode();
|
||||
if (node == null)
|
||||
return null;
|
||||
return node.getParentNode();
|
||||
}
|
||||
|
||||
private Node getRootNode()
|
||||
{
|
||||
return getServiceNode().getRootNode();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Device
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Device getDevice()
|
||||
{
|
||||
return new Device(getRootNode(), getDeviceNode());
|
||||
}
|
||||
|
||||
public Device getRootDevice()
|
||||
{
|
||||
return getDevice().getRootDevice();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// serviceType
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String SERVICE_TYPE = "serviceType";
|
||||
|
||||
public void setServiceType(String value)
|
||||
{
|
||||
getServiceNode().setNode(SERVICE_TYPE, value);
|
||||
}
|
||||
|
||||
public String getServiceType()
|
||||
{
|
||||
return getServiceNode().getNodeValue(SERVICE_TYPE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// serviceID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String SERVICE_ID = "serviceId";
|
||||
|
||||
public void setServiceID(String value)
|
||||
{
|
||||
getServiceNode().setNode(SERVICE_ID, value);
|
||||
}
|
||||
|
||||
public String getServiceID()
|
||||
{
|
||||
return getServiceNode().getNodeValue(SERVICE_ID);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/03/03)
|
||||
private boolean isURL(String referenceUrl, String url)
|
||||
{
|
||||
if (referenceUrl ==null || url == null)
|
||||
return false;
|
||||
boolean ret = url.equals(referenceUrl);
|
||||
if (ret == true)
|
||||
return true;
|
||||
String relativeRefUrl = HTTP.toRelativeURL(referenceUrl, false);
|
||||
ret = url.equals(relativeRefUrl);
|
||||
if (ret == true)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SCPDURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String SCPDURL = "SCPDURL";
|
||||
|
||||
public void setSCPDURL(String value)
|
||||
{
|
||||
getServiceNode().setNode(SCPDURL, value);
|
||||
}
|
||||
|
||||
public String getSCPDURL()
|
||||
{
|
||||
return getServiceNode().getNodeValue(SCPDURL);
|
||||
}
|
||||
|
||||
public boolean isSCPDURL(String url)
|
||||
{
|
||||
return isURL(getSCPDURL(), url);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// controlURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String CONTROL_URL = "controlURL";
|
||||
|
||||
public void setControlURL(String value)
|
||||
{
|
||||
getServiceNode().setNode(CONTROL_URL, value);
|
||||
}
|
||||
|
||||
public String getControlURL()
|
||||
{
|
||||
return getServiceNode().getNodeValue(CONTROL_URL);
|
||||
}
|
||||
|
||||
public boolean isControlURL(String url)
|
||||
{
|
||||
return isURL(getControlURL(), url);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// eventSubURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String EVENT_SUB_URL = "eventSubURL";
|
||||
|
||||
public void setEventSubURL(String value)
|
||||
{
|
||||
getServiceNode().setNode(EVENT_SUB_URL, value);
|
||||
}
|
||||
|
||||
public String getEventSubURL()
|
||||
{
|
||||
return getServiceNode().getNodeValue(EVENT_SUB_URL);
|
||||
}
|
||||
|
||||
public boolean isEventSubURL(String url)
|
||||
{
|
||||
return isURL(getEventSubURL(), url);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SCPD node
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean loadSCPD(String scpdStr) throws InvalidDescriptionException
|
||||
{
|
||||
try {
|
||||
Parser parser = UPnP.getXMLParser();
|
||||
Node scpdNode = parser.parse(scpdStr);
|
||||
if (scpdNode == null)
|
||||
return false;
|
||||
ServiceData data = getServiceData();
|
||||
data.setSCPDNode(scpdNode);
|
||||
}
|
||||
catch (ParserException e) {
|
||||
throw new InvalidDescriptionException(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean loadSCPD(File file) throws ParserException
|
||||
{
|
||||
Parser parser = UPnP.getXMLParser();
|
||||
Node scpdNode = parser.parse(file);
|
||||
if (scpdNode == null)
|
||||
return false;
|
||||
ServiceData data = getServiceData();
|
||||
data.setSCPDNode(scpdNode);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Node getSCPDNode(URL scpdUrl) throws ParserException
|
||||
{
|
||||
Parser parser = UPnP.getXMLParser();
|
||||
return parser.parse(scpdUrl);
|
||||
}
|
||||
|
||||
private Node getSCPDNode(File scpdFile) throws ParserException
|
||||
{
|
||||
Parser parser = UPnP.getXMLParser();
|
||||
return parser.parse(scpdFile);
|
||||
}
|
||||
|
||||
private Node getSCPDNode()
|
||||
{
|
||||
ServiceData data = getServiceData();
|
||||
Node scpdNode = data.getSCPDNode();
|
||||
if (scpdNode != null)
|
||||
return scpdNode;
|
||||
|
||||
String scpdURLStr = getSCPDURL();
|
||||
try {
|
||||
URL scpdUrl = new URL(scpdURLStr);
|
||||
scpdNode = getSCPDNode(scpdUrl);
|
||||
}
|
||||
catch (Exception e1) {
|
||||
Device rootDev = getRootDevice();
|
||||
String urlBaseStr = rootDev.getURLBase();
|
||||
// Thanks for Steven Yen (2003/09/03)
|
||||
if (urlBaseStr == null || urlBaseStr.length() <= 0) {
|
||||
String location = rootDev.getLocation();
|
||||
String locationHost = HTTP.getHost(location);
|
||||
int locationPort = HTTP.getPort(location);
|
||||
urlBaseStr = HTTP.getRequestHostURL(locationHost, locationPort);
|
||||
}
|
||||
scpdURLStr = HTTP.toRelativeURL(scpdURLStr);
|
||||
String newScpdURLStr = urlBaseStr + scpdURLStr;
|
||||
try {
|
||||
URL newScpdURL = new URL(newScpdURLStr);
|
||||
scpdNode = getSCPDNode(newScpdURL);
|
||||
}
|
||||
catch (Exception e2) {
|
||||
newScpdURLStr = HTTP.getAbsoluteURL(urlBaseStr, scpdURLStr);
|
||||
try {
|
||||
URL newScpdURL = new URL(newScpdURLStr);
|
||||
scpdNode = getSCPDNode(newScpdURL);
|
||||
}
|
||||
catch (Exception e3) {
|
||||
newScpdURLStr = rootDev.getDescriptionFilePath() + scpdURLStr;
|
||||
try {
|
||||
scpdNode = getSCPDNode(new File(newScpdURLStr));
|
||||
}
|
||||
catch (Exception e4) {
|
||||
Debug.warning(e4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data.setSCPDNode(scpdNode);
|
||||
|
||||
return scpdNode;
|
||||
}
|
||||
|
||||
public byte[] getSCPDData()
|
||||
{
|
||||
Node scpdNode = getSCPDNode();
|
||||
if (scpdNode == null)
|
||||
return new byte[0];
|
||||
// Thanks for Mikael Hakman (04/25/05)
|
||||
String desc = new String();
|
||||
desc += UPnP.XML_DECLARATION;
|
||||
desc += "\n";
|
||||
desc += scpdNode.toString();
|
||||
return desc.getBytes();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// actionList
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ActionList getActionList()
|
||||
{
|
||||
ActionList actionList = new ActionList();
|
||||
Node scdpNode = getSCPDNode();
|
||||
if (scdpNode == null)
|
||||
return actionList;
|
||||
Node actionListNode = scdpNode.getNode(ActionList.ELEM_NAME);
|
||||
if (actionListNode == null)
|
||||
return actionList;
|
||||
Node serviceNode = getServiceNode();
|
||||
int nNode = actionListNode.getNNodes();
|
||||
for (int n=0; n<nNode; n++) {
|
||||
Node node = actionListNode.getNode(n);
|
||||
if (Action.isActionNode(node) == false)
|
||||
continue;
|
||||
Action action = new Action(serviceNode, node);
|
||||
actionList.add(action);
|
||||
}
|
||||
return actionList;
|
||||
}
|
||||
|
||||
public Action getAction(String actionName)
|
||||
{
|
||||
ActionList actionList = getActionList();
|
||||
int nActions = actionList.size();
|
||||
for (int n=0; n<nActions; n++) {
|
||||
Action action = actionList.getAction(n);
|
||||
String name = action.getName();
|
||||
if (name == null)
|
||||
continue;
|
||||
if (name.equals(actionName) == true)
|
||||
return action;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// serviceStateTable
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ServiceStateTable getServiceStateTable()
|
||||
{
|
||||
ServiceStateTable stateTable = new ServiceStateTable();
|
||||
Node stateTableNode = getSCPDNode().getNode(ServiceStateTable.ELEM_NAME);
|
||||
if (stateTableNode == null)
|
||||
return stateTable;
|
||||
Node serviceNode = getServiceNode();
|
||||
int nNode = stateTableNode.getNNodes();
|
||||
for (int n=0; n<nNode; n++) {
|
||||
Node node = stateTableNode.getNode(n);
|
||||
if (StateVariable.isStateVariableNode(node) == false)
|
||||
continue;
|
||||
StateVariable serviceVar = new StateVariable(serviceNode, node);
|
||||
stateTable.add(serviceVar);
|
||||
}
|
||||
return stateTable;
|
||||
}
|
||||
|
||||
public StateVariable getStateVariable(String name)
|
||||
{
|
||||
ServiceStateTable stateTable = getServiceStateTable();
|
||||
int tableSize = stateTable.size();
|
||||
for (int n=0; n<tableSize; n++) {
|
||||
StateVariable var = stateTable.getStateVariable(n);
|
||||
String varName = var.getName();
|
||||
if (varName == null)
|
||||
continue;
|
||||
if (varName.equals(name) == true)
|
||||
return var;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean hasStateVariable(String name)
|
||||
{
|
||||
return (getStateVariable(name) != null ) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UserData
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean isService(String name)
|
||||
{
|
||||
if (name == null)
|
||||
return false;
|
||||
if (name.endsWith(getServiceType()) == true)
|
||||
return true;
|
||||
if (name.endsWith(getServiceID()) == true)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UserData
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ServiceData getServiceData()
|
||||
{
|
||||
Node node = getServiceNode();
|
||||
ServiceData userData = (ServiceData)node.getUserData();
|
||||
if (userData == null) {
|
||||
userData = new ServiceData();
|
||||
node.setUserData(userData);
|
||||
userData.setNode(node);
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Notify
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String getNotifyServiceTypeNT()
|
||||
{
|
||||
return getServiceType();
|
||||
}
|
||||
|
||||
private String getNotifyServiceTypeUSN()
|
||||
{
|
||||
return getDevice().getUDN() + "::" + getServiceType();
|
||||
}
|
||||
|
||||
public void announce(String bindAddr)
|
||||
{
|
||||
// uuid:device-UUID::urn:schemas-upnp-org:service:serviceType:v
|
||||
Device rootDev = getRootDevice();
|
||||
String devLocation = rootDev.getLocationURL(bindAddr);
|
||||
String serviceNT = getNotifyServiceTypeNT();
|
||||
String serviceUSN = getNotifyServiceTypeUSN();
|
||||
|
||||
Device dev = getDevice();
|
||||
|
||||
SSDPNotifyRequest ssdpReq = new SSDPNotifyRequest();
|
||||
ssdpReq.setServer(UPnP.getServerName());
|
||||
ssdpReq.setLeaseTime(dev.getLeaseTime());
|
||||
ssdpReq.setLocation(devLocation);
|
||||
ssdpReq.setNTS(NTS.ALIVE);
|
||||
ssdpReq.setNT(serviceNT);
|
||||
ssdpReq.setUSN(serviceUSN);
|
||||
|
||||
SSDPNotifySocket ssdpSock = new SSDPNotifySocket(bindAddr);
|
||||
Device.notifyWait();
|
||||
ssdpSock.post(ssdpReq);
|
||||
}
|
||||
|
||||
public void byebye(String bindAddr)
|
||||
{
|
||||
// uuid:device-UUID::urn:schemas-upnp-org:service:serviceType:v
|
||||
|
||||
String devNT = getNotifyServiceTypeNT();
|
||||
String devUSN = getNotifyServiceTypeUSN();
|
||||
|
||||
SSDPNotifyRequest ssdpReq = new SSDPNotifyRequest();
|
||||
ssdpReq.setNTS(NTS.BYEBYE);
|
||||
ssdpReq.setNT(devNT);
|
||||
ssdpReq.setUSN(devUSN);
|
||||
|
||||
SSDPNotifySocket ssdpSock = new SSDPNotifySocket(bindAddr);
|
||||
Device.notifyWait();
|
||||
ssdpSock.post(ssdpReq);
|
||||
}
|
||||
|
||||
public boolean serviceSearchResponse(SSDPPacket ssdpPacket)
|
||||
{
|
||||
String ssdpST = ssdpPacket.getST();
|
||||
|
||||
if (ssdpST == null)
|
||||
return false;
|
||||
|
||||
Device dev = getDevice();
|
||||
|
||||
String serviceNT = getNotifyServiceTypeNT();
|
||||
String serviceUSN = getNotifyServiceTypeUSN();
|
||||
|
||||
if (ST.isAllDevice(ssdpST) == true) {
|
||||
dev.postSearchResponse(ssdpPacket, serviceNT, serviceUSN);
|
||||
}
|
||||
else if (ST.isURNService(ssdpST) == true) {
|
||||
String serviceType = getServiceType();
|
||||
if (ssdpST.equals(serviceType) == true)
|
||||
dev.postSearchResponse(ssdpPacket, serviceType, serviceUSN);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// QueryListener
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setQueryListener(QueryListener queryListener)
|
||||
{
|
||||
ServiceStateTable stateTable = getServiceStateTable();
|
||||
int tableSize = stateTable.size();
|
||||
for (int n=0; n<tableSize; n++) {
|
||||
StateVariable var = stateTable.getStateVariable(n);
|
||||
var.setQueryListener(queryListener);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Subscription
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SubscriberList getSubscriberList()
|
||||
{
|
||||
return getServiceData().getSubscriberList();
|
||||
}
|
||||
|
||||
public void addSubscriber(Subscriber sub)
|
||||
{
|
||||
getSubscriberList().add(sub);
|
||||
}
|
||||
|
||||
public void removeSubscriber(Subscriber sub)
|
||||
{
|
||||
getSubscriberList().remove(sub);
|
||||
}
|
||||
|
||||
public Subscriber getSubscriber(String name)
|
||||
{
|
||||
SubscriberList subList = getSubscriberList();
|
||||
int subListCnt = subList.size();
|
||||
for (int n=0; n<subListCnt; n++) {
|
||||
Subscriber sub = subList.getSubscriber(n);
|
||||
if (sub == null)
|
||||
continue;
|
||||
String sid = sub.getSID();
|
||||
if (sid == null)
|
||||
continue;
|
||||
if (sid.equals(name) == true)
|
||||
return sub;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean notify(Subscriber sub, StateVariable stateVar)
|
||||
{
|
||||
String varName = stateVar.getName();
|
||||
String value = stateVar.getValue();
|
||||
|
||||
String host = sub.getDeliveryHost();
|
||||
int port = sub.getDeliveryPort();
|
||||
|
||||
NotifyRequest notifyReq = new NotifyRequest();
|
||||
notifyReq.setRequest(sub, varName, value);
|
||||
|
||||
HTTPResponse res = notifyReq.post(host, port);
|
||||
if (res.isSuccessful() == false)
|
||||
return false;
|
||||
|
||||
sub.incrementNotifyCount();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void notify(StateVariable stateVar)
|
||||
{
|
||||
SubscriberList subList = getSubscriberList();
|
||||
int subListCnt;
|
||||
Subscriber subs[];
|
||||
|
||||
// Remove expired subscribers.
|
||||
subListCnt = subList.size();
|
||||
subs = new Subscriber[subListCnt];
|
||||
for (int n=0; n<subListCnt; n++)
|
||||
subs[n] = subList.getSubscriber(n);
|
||||
for (int n=0; n<subListCnt; n++) {
|
||||
Subscriber sub = subs[n];
|
||||
if (sub.isExpired() == true)
|
||||
removeSubscriber(sub);
|
||||
}
|
||||
|
||||
// Notify to subscribers.
|
||||
subListCnt = subList.size();
|
||||
subs = new Subscriber[subListCnt];
|
||||
for (int n=0; n<subListCnt; n++)
|
||||
subs[n] = subList.getSubscriber(n);
|
||||
for (int n=0; n<subListCnt; n++) {
|
||||
Subscriber sub = subs[n];
|
||||
if (notify(sub, stateVar) == false) {
|
||||
/* Don't remove for NMPR specification.
|
||||
removeSubscriber(sub);
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void notifyAllStateVariables()
|
||||
{
|
||||
ServiceStateTable stateTable = getServiceStateTable();
|
||||
int tableSize = stateTable.size();
|
||||
for (int n=0; n<tableSize; n++) {
|
||||
StateVariable var = stateTable.getStateVariable(n);
|
||||
if (var.isSendEvents() == true)
|
||||
notify(var);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getSID()
|
||||
{
|
||||
return getServiceData().getSID();
|
||||
}
|
||||
|
||||
public void setSID(String id)
|
||||
{
|
||||
getServiceData().setSID(id);
|
||||
}
|
||||
|
||||
public void clearSID()
|
||||
{
|
||||
setSID("");
|
||||
setTimeout(0);
|
||||
}
|
||||
|
||||
public boolean hasSID()
|
||||
{
|
||||
return StringUtil.hasData(getSID());
|
||||
}
|
||||
|
||||
public boolean isSubscribed()
|
||||
{
|
||||
return hasSID();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Timeout
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public long getTimeout()
|
||||
{
|
||||
return getServiceData().getTimeout();
|
||||
}
|
||||
|
||||
public void setTimeout(long value)
|
||||
{
|
||||
getServiceData().setTimeout(value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// AcionListener
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setActionListener(ActionListener listener)
|
||||
{
|
||||
ActionList actionList = getActionList();
|
||||
int nActions = actionList.size();
|
||||
for (int n=0; n<nActions; n++) {
|
||||
Action action = actionList.getAction(n);
|
||||
action.setActionListener(listener);
|
||||
}
|
||||
}
|
||||
}
|
53
router/java/src/org/cybergarage/upnp/ServiceList.java
Normal file
53
router/java/src/org/cybergarage/upnp/ServiceList.java
Normal file
@ -0,0 +1,53 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ServiceList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/04/02
|
||||
* - first revision.
|
||||
* 06/18/03
|
||||
* - Added caching a ArrayIndexOfBound exception.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ServiceList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 6372904993975135597L;
|
||||
public final static String ELEM_NAME = "serviceList";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ServiceList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Service getService(int n)
|
||||
{
|
||||
Object obj = null;
|
||||
try {
|
||||
obj = get(n);
|
||||
}
|
||||
catch (Exception e) {};
|
||||
return (Service)obj;
|
||||
}
|
||||
}
|
||||
|
46
router/java/src/org/cybergarage/upnp/ServiceStateTable.java
Normal file
46
router/java/src/org/cybergarage/upnp/ServiceStateTable.java
Normal file
@ -0,0 +1,46 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ServiceStateTable.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 12/06/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ServiceStateTable extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 7626909231678469365L;
|
||||
public final static String ELEM_NAME = "serviceStateTable";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ServiceStateTable()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public StateVariable getStateVariable(int n)
|
||||
{
|
||||
return (StateVariable)get(n);
|
||||
}
|
||||
}
|
||||
|
374
router/java/src/org/cybergarage/upnp/StateVariable.java
Normal file
374
router/java/src/org/cybergarage/upnp/StateVariable.java
Normal file
@ -0,0 +1,374 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: StateVariable.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/06/02
|
||||
* - first revision.
|
||||
* 06/17/03
|
||||
* - Added setSendEvents(), isSendEvents().
|
||||
* - Changed to send a event after check the eventing state using isSendEvents().
|
||||
* 01/04/04
|
||||
* - Added UPnP status methods.
|
||||
* 01/06/04
|
||||
* - Added the following methods.
|
||||
* getQueryListener()
|
||||
* setQueryListener()
|
||||
* performQueryListener()
|
||||
* 01/07/04
|
||||
* - Added StateVariable() and set();
|
||||
* - Changed performQueryListener() to use a copy of the StateVariable.
|
||||
* 03/27/04
|
||||
* - Thanks for Adavy
|
||||
* - Added getAllowedValueList() and getAllowedValueRange().
|
||||
* 05/11/04
|
||||
* - Added hasAllowedValueList() and hasAllowedValueRange().
|
||||
* 07/09/04
|
||||
* - Thanks for Dimas <cyberrate@users.sourceforge.net> and Stefano Lenzi <kismet-sl@users.sourceforge.net>
|
||||
* - Changed postQuerylAction() to set the status code to the UPnPStatus.
|
||||
* 11/09/04
|
||||
* - Theo Beisch <theo.beisch@gmx.de>
|
||||
* - Changed StateVariable::setValue() to update and send the event when the value is not equal to the current value.
|
||||
* 11/19/04
|
||||
* - Rick Keiner <rick@emanciple.com>
|
||||
* - Fixed setValue() to compare only when the current value is not null.
|
||||
* 02/28/05
|
||||
* - Changed getAllowedValueList() to use AllowedValue instead of String as the member.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
import org.cybergarage.upnp.control.*;
|
||||
import org.cybergarage.upnp.xml.*;
|
||||
|
||||
public class StateVariable extends NodeData
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String ELEM_NAME = "stateVariable";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node stateVariableNode;
|
||||
private Node serviceNode;
|
||||
|
||||
public Node getServiceNode()
|
||||
{
|
||||
return serviceNode;
|
||||
}
|
||||
|
||||
public Service getService()
|
||||
{
|
||||
Node serviceNode = getServiceNode();
|
||||
if (serviceNode == null)
|
||||
return null;
|
||||
return new Service(serviceNode);
|
||||
}
|
||||
|
||||
public Node getStateVariableNode()
|
||||
{
|
||||
return stateVariableNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public StateVariable()
|
||||
{
|
||||
this.serviceNode = null;
|
||||
this.stateVariableNode = new Node();
|
||||
}
|
||||
|
||||
public StateVariable(Node serviceNode, Node stateVarNode)
|
||||
{
|
||||
this.serviceNode = serviceNode;
|
||||
this.stateVariableNode = stateVarNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// isStateVariableNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static boolean isStateVariableNode(Node node)
|
||||
{
|
||||
return StateVariable.ELEM_NAME.equals(node.getName());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// name
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String NAME = "name";
|
||||
|
||||
public void setName(String value)
|
||||
{
|
||||
getStateVariableNode().setNode(NAME, value);
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return getStateVariableNode().getNodeValue(NAME);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// dataType
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String DATATYPE = "dataType";
|
||||
|
||||
public void setDataType(String value)
|
||||
{
|
||||
getStateVariableNode().setNode(DATATYPE, value);
|
||||
}
|
||||
|
||||
public String getDataType()
|
||||
{
|
||||
return getStateVariableNode().getNodeValue(DATATYPE);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// dataType
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String SENDEVENTS = "sendEvents";
|
||||
private final static String SENDEVENTS_YES = "yes";
|
||||
private final static String SENDEVENTS_NO = "no";
|
||||
|
||||
public void setSendEvents(boolean state)
|
||||
{
|
||||
getStateVariableNode().setAttribute(SENDEVENTS, (state == true) ? SENDEVENTS_YES : SENDEVENTS_NO);
|
||||
}
|
||||
|
||||
public boolean isSendEvents()
|
||||
{
|
||||
String state = getStateVariableNode().getAttributeValue(SENDEVENTS);
|
||||
if (state == null)
|
||||
return false;
|
||||
if (state.equalsIgnoreCase(SENDEVENTS_YES) == true)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// set
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void set(StateVariable stateVar)
|
||||
{
|
||||
setName(stateVar.getName());
|
||||
setValue(stateVar.getValue());
|
||||
setDataType(stateVar.getDataType());
|
||||
setSendEvents(stateVar.isSendEvents());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UserData
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public StateVariableData getStateVariableData ()
|
||||
{
|
||||
Node node = getStateVariableNode();
|
||||
StateVariableData userData = (StateVariableData)node.getUserData();
|
||||
if (userData == null) {
|
||||
userData = new StateVariableData();
|
||||
node.setUserData(userData);
|
||||
userData.setNode(node);
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Value
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setValue(String value)
|
||||
{
|
||||
// Thnaks for Tho Beisch (11/09/04)
|
||||
String currValue = getStateVariableData().getValue();
|
||||
// Thnaks for Tho Rick Keiner (11/18/04)
|
||||
if (currValue != null && currValue.equals(value) == true)
|
||||
return;
|
||||
|
||||
getStateVariableData().setValue(value);
|
||||
|
||||
// notify event
|
||||
Service service = getService();
|
||||
if (service == null)
|
||||
return;
|
||||
if (isSendEvents() == false)
|
||||
return;
|
||||
service.notify(this);
|
||||
}
|
||||
|
||||
public void setValue(int value)
|
||||
{
|
||||
setValue(Integer.toString(value));
|
||||
}
|
||||
|
||||
public void setValue(long value)
|
||||
{
|
||||
setValue(Long.toString(value));
|
||||
}
|
||||
|
||||
public String getValue()
|
||||
{
|
||||
return getStateVariableData().getValue();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// AllowedValueList
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public AllowedValueList getAllowedValueList()
|
||||
{
|
||||
AllowedValueList valueList= new AllowedValueList();
|
||||
Node valueListNode = getStateVariableNode().getNode(AllowedValueList.ELEM_NAME);
|
||||
if (valueListNode == null)
|
||||
return valueList;
|
||||
int nNode = valueListNode.getNNodes();
|
||||
for (int n=0; n<nNode; n++) {
|
||||
Node node = valueListNode.getNode(n);
|
||||
if (AllowedValue.isAllowedValueNode(node) == false)
|
||||
continue;
|
||||
AllowedValue allowedVal = new AllowedValue(node);
|
||||
valueList.add(allowedVal);
|
||||
}
|
||||
return valueList;
|
||||
}
|
||||
|
||||
public boolean hasAllowedValueList()
|
||||
{
|
||||
AllowedValueList valueList = getAllowedValueList();
|
||||
return (0 < valueList.size()) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// AllowedValueRange
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public AllowedValueRange getAllowedValueRange()
|
||||
{
|
||||
Node valueRangeNode = getStateVariableNode().getNode(AllowedValueRange.ELEM_NAME);
|
||||
if (valueRangeNode == null)
|
||||
return null;
|
||||
return new AllowedValueRange(valueRangeNode);
|
||||
}
|
||||
|
||||
public boolean hasAllowedValueRange()
|
||||
{
|
||||
return (getAllowedValueRange() != null) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// queryAction
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public QueryListener getQueryListener()
|
||||
{
|
||||
return getStateVariableData().getQueryListener();
|
||||
}
|
||||
|
||||
public void setQueryListener(QueryListener listener)
|
||||
{
|
||||
getStateVariableData().setQueryListener(listener);
|
||||
}
|
||||
|
||||
public boolean performQueryListener(QueryRequest queryReq)
|
||||
{
|
||||
QueryListener listener = getQueryListener();
|
||||
if (listener == null)
|
||||
return false;
|
||||
QueryResponse queryRes = new QueryResponse();
|
||||
StateVariable retVar = new StateVariable();
|
||||
retVar.set(this);
|
||||
retVar.setValue("");
|
||||
retVar.setStatus(UPnPStatus.INVALID_VAR);
|
||||
if (listener.queryControlReceived(retVar) == true) {
|
||||
queryRes.setResponse(retVar);
|
||||
}
|
||||
else {
|
||||
UPnPStatus upnpStatus = retVar.getStatus();
|
||||
queryRes.setFaultResponse(upnpStatus.getCode(), upnpStatus.getDescription());
|
||||
}
|
||||
queryReq.post(queryRes);
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ActionControl
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public QueryResponse getQueryResponse()
|
||||
{
|
||||
return getStateVariableData().getQueryResponse();
|
||||
}
|
||||
|
||||
private void setQueryResponse(QueryResponse res)
|
||||
{
|
||||
getStateVariableData().setQueryResponse(res);
|
||||
}
|
||||
|
||||
public UPnPStatus getQueryStatus()
|
||||
{
|
||||
return getQueryResponse().getUPnPError();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ActionControl
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean postQuerylAction()
|
||||
{
|
||||
QueryRequest queryReq = new QueryRequest();
|
||||
queryReq.setRequest(this);
|
||||
if (Debug.isOn() == true)
|
||||
queryReq.print();
|
||||
QueryResponse queryRes = queryReq.post();
|
||||
if (Debug.isOn() == true)
|
||||
queryRes.print();
|
||||
setQueryResponse(queryRes);
|
||||
// Thanks for Dimas <cyberrate@users.sourceforge.net> and Stefano Lenzi <kismet-sl@users.sourceforge.net> (07/09/04)
|
||||
if (queryRes.isSuccessful() == false) {
|
||||
setValue(queryRes.getReturnValue());
|
||||
return false;
|
||||
}
|
||||
setValue(queryRes.getReturnValue());
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UPnPStatus
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private UPnPStatus upnpStatus = new UPnPStatus();
|
||||
|
||||
public void setStatus(int code, String descr)
|
||||
{
|
||||
upnpStatus.setCode(code);
|
||||
upnpStatus.setDescription(descr);
|
||||
}
|
||||
|
||||
public void setStatus(int code)
|
||||
{
|
||||
setStatus(code, UPnPStatus.code2String(code));
|
||||
}
|
||||
|
||||
public UPnPStatus getStatus()
|
||||
{
|
||||
return upnpStatus;
|
||||
}
|
||||
}
|
232
router/java/src/org/cybergarage/upnp/UPnP.java
Normal file
232
router/java/src/org/cybergarage/upnp/UPnP.java
Normal file
@ -0,0 +1,232 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: UPnP.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 05/13/03
|
||||
* - Added support for IPv6 and loopback address.
|
||||
* 12/26/03
|
||||
* - Added support for XML Parser
|
||||
* 06/18/03
|
||||
* - Added INMPR03 and INMPR03_VERSION.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
import org.cybergarage.upnp.ssdp.*;
|
||||
//import org.cybergarage.util.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.xml.parser.*;
|
||||
import org.cybergarage.soap.*;
|
||||
import org.cybergarage.net.*;
|
||||
|
||||
public class UPnP
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String NAME = "CyberLink";
|
||||
public final static String VERSION = "1.7";
|
||||
|
||||
public final static int SERVER_RETRY_COUNT = 100;
|
||||
public final static int DEFAULT_EXPIRED_DEVICE_EXTRA_TIME = 60;
|
||||
|
||||
public final static String getServerName()
|
||||
{
|
||||
String osName = System.getProperty("os.name");
|
||||
String osVer = System.getProperty("os.version");
|
||||
return osName + "/" + osVer + " UPnP/1.0 " + NAME + "/" + VERSION;
|
||||
}
|
||||
|
||||
public final static String INMPR03 = "INMPR03";
|
||||
public final static String INMPR03_VERSION = "1.0";
|
||||
public final static int INMPR03_DISCOVERY_OVER_WIRELESS_COUNT = 4;
|
||||
|
||||
public final static String XML_DECLARATION = "<?xml version=\"1.0\"?>";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Enable / Disable
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static int USE_ONLY_IPV6_ADDR = 1;
|
||||
public final static int USE_LOOPBACK_ADDR = 2;
|
||||
public final static int USE_IPV6_LINK_LOCAL_SCOPE = 3;
|
||||
public final static int USE_IPV6_SUBNET_SCOPE = 4;
|
||||
public final static int USE_IPV6_ADMINISTRATIVE_SCOPE = 5;
|
||||
public final static int USE_IPV6_SITE_LOCAL_SCOPE = 6;
|
||||
public final static int USE_IPV6_GLOBAL_SCOPE = 7;
|
||||
public final static int USE_SSDP_SEARCHRESPONSE_MULTIPLE_INTERFACES = 8;
|
||||
public final static int USE_ONLY_IPV4_ADDR = 9;
|
||||
|
||||
public final static void setEnable(int value)
|
||||
{
|
||||
switch (value) {
|
||||
case USE_ONLY_IPV6_ADDR:
|
||||
{
|
||||
HostInterface.USE_ONLY_IPV6_ADDR = true;
|
||||
}
|
||||
break;
|
||||
case USE_ONLY_IPV4_ADDR:
|
||||
{
|
||||
HostInterface.USE_ONLY_IPV4_ADDR = true;
|
||||
}
|
||||
break;
|
||||
case USE_LOOPBACK_ADDR:
|
||||
{
|
||||
HostInterface.USE_LOOPBACK_ADDR = true;
|
||||
}
|
||||
break;
|
||||
case USE_IPV6_LINK_LOCAL_SCOPE:
|
||||
{
|
||||
SSDP.setIPv6Address(SSDP.IPV6_LINK_LOCAL_ADDRESS);
|
||||
}
|
||||
break;
|
||||
case USE_IPV6_SUBNET_SCOPE:
|
||||
{
|
||||
SSDP.setIPv6Address(SSDP.IPV6_SUBNET_ADDRESS);
|
||||
}
|
||||
break;
|
||||
case USE_IPV6_ADMINISTRATIVE_SCOPE:
|
||||
{
|
||||
SSDP.setIPv6Address(SSDP.IPV6_ADMINISTRATIVE_ADDRESS);
|
||||
}
|
||||
break;
|
||||
case USE_IPV6_SITE_LOCAL_SCOPE:
|
||||
{
|
||||
SSDP.setIPv6Address(SSDP.IPV6_SITE_LOCAL_ADDRESS);
|
||||
}
|
||||
break;
|
||||
case USE_IPV6_GLOBAL_SCOPE:
|
||||
{
|
||||
SSDP.setIPv6Address(SSDP.IPV6_GLOBAL_ADDRESS);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public final static void setDisable(int value)
|
||||
{
|
||||
switch (value) {
|
||||
case USE_ONLY_IPV6_ADDR:
|
||||
{
|
||||
HostInterface.USE_ONLY_IPV6_ADDR = false;
|
||||
}
|
||||
break;
|
||||
case USE_ONLY_IPV4_ADDR:
|
||||
{
|
||||
HostInterface.USE_ONLY_IPV4_ADDR = false;
|
||||
}
|
||||
break;
|
||||
case USE_LOOPBACK_ADDR:
|
||||
{
|
||||
HostInterface.USE_LOOPBACK_ADDR = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public final static boolean isEnabled(int value)
|
||||
{
|
||||
switch (value) {
|
||||
case USE_ONLY_IPV6_ADDR:
|
||||
{
|
||||
return HostInterface.USE_ONLY_IPV6_ADDR;
|
||||
}
|
||||
case USE_ONLY_IPV4_ADDR:
|
||||
{
|
||||
return HostInterface.USE_ONLY_IPV4_ADDR;
|
||||
}
|
||||
case USE_LOOPBACK_ADDR:
|
||||
{
|
||||
return HostInterface.USE_LOOPBACK_ADDR;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UUID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final String toUUID(int seed)
|
||||
{
|
||||
String id = Integer.toString((int)(seed & 0xFFFF), 16);
|
||||
int idLen = id.length();
|
||||
String uuid = "";
|
||||
for (int n=0; n<(4-idLen); n++)
|
||||
uuid += "0";
|
||||
uuid += id;
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public static final String createUUID()
|
||||
{
|
||||
long time1 = System.currentTimeMillis();
|
||||
long time2 = (long)((double)System.currentTimeMillis() * Math.random());
|
||||
return
|
||||
toUUID((int)(time1 & 0xFFFF)) + "-" +
|
||||
toUUID((int)((time1 >> 32) | 0xA000) & 0xFFFF) + "-" +
|
||||
toUUID((int)(time2 & 0xFFFF)) + "-" +
|
||||
toUUID((int)((time2 >> 32) | 0xE000) & 0xFFFF);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// XML Parser
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static Parser xmlParser;
|
||||
|
||||
public final static void setXMLParser(Parser parser)
|
||||
{
|
||||
xmlParser = parser;
|
||||
SOAP.setXMLParser(parser);
|
||||
}
|
||||
|
||||
public final static Parser getXMLParser()
|
||||
{
|
||||
return xmlParser;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Initialize
|
||||
////////////////////////////////////////////////
|
||||
|
||||
static
|
||||
{
|
||||
////////////////////////////
|
||||
// Interface Option
|
||||
////////////////////////////
|
||||
|
||||
setXMLParser(new JaxpParser());
|
||||
//setXMLParser(new kXML2Parser());
|
||||
|
||||
////////////////////////////
|
||||
// Interface Option
|
||||
////////////////////////////
|
||||
/*
|
||||
if (HostInterface.hasIPv6Addresses() == true)
|
||||
setEnable(USE_ONLY_IPV6_ADDR);
|
||||
*/
|
||||
|
||||
////////////////////////////
|
||||
// Debug Option
|
||||
////////////////////////////
|
||||
|
||||
//Debug.on();
|
||||
}
|
||||
|
||||
public final static void initialize()
|
||||
{
|
||||
// Dummy function to call UPnP.static
|
||||
}
|
||||
|
||||
}
|
81
router/java/src/org/cybergarage/upnp/UPnPStatus.java
Normal file
81
router/java/src/org/cybergarage/upnp/UPnPStatus.java
Normal file
@ -0,0 +1,81 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: UPnPStatus.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 01/03/04
|
||||
* - Changed the class name from UPnPError to UPnPStatus.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp;
|
||||
|
||||
public class UPnPStatus
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Code
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static final int INVALID_ACTION = 401;
|
||||
public static final int INVALID_ARGS = 402;
|
||||
public static final int OUT_OF_SYNC = 403;
|
||||
public static final int INVALID_VAR = 404;
|
||||
public static final int PRECONDITION_FAILED = 412;
|
||||
public static final int ACTION_FAILED = 501;
|
||||
|
||||
public static final String code2String(int code)
|
||||
{
|
||||
switch (code) {
|
||||
case INVALID_ACTION: return "Invalid Action";
|
||||
case INVALID_ARGS: return "Invalid Args";
|
||||
case OUT_OF_SYNC: return "Out of Sync";
|
||||
case INVALID_VAR: return "Invalid Var";
|
||||
case PRECONDITION_FAILED: return "Precondition Failed";
|
||||
case ACTION_FAILED: return "Action Failed";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private int code;
|
||||
private String description;
|
||||
|
||||
public UPnPStatus()
|
||||
{
|
||||
setCode(0);
|
||||
setDescription("");
|
||||
}
|
||||
|
||||
public UPnPStatus(int code, String desc)
|
||||
{
|
||||
setCode(code);
|
||||
setDescription(desc);
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ActionListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/16/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public interface ActionListener
|
||||
{
|
||||
public boolean actionControlReceived(Action action);
|
||||
}
|
145
router/java/src/org/cybergarage/upnp/control/ActionRequest.java
Normal file
145
router/java/src/org/cybergarage/upnp/control/ActionRequest.java
Normal file
@ -0,0 +1,145 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ControlRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
* 05/09/05
|
||||
* - Changed getActionName() to return when the delimiter is not found.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.soap.*;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class ActionRequest extends ControlRequest
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ActionRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public ActionRequest(HTTPRequest httpReq)
|
||||
{
|
||||
set(httpReq);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Action
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Node getActionNode()
|
||||
{
|
||||
Node bodyNode = getBodyNode();
|
||||
if (bodyNode == null)
|
||||
return null;
|
||||
if (bodyNode.hasNodes() == false)
|
||||
return null;
|
||||
return bodyNode.getNode(0);
|
||||
}
|
||||
|
||||
public String getActionName()
|
||||
{
|
||||
Node node = getActionNode();
|
||||
if (node == null)
|
||||
return "";
|
||||
String name = node.getName();
|
||||
if (name == null)
|
||||
return "";
|
||||
int idx = name.indexOf(SOAP.DELIM)+1;
|
||||
if (idx < 0)
|
||||
return "";
|
||||
return name.substring(idx, name.length());
|
||||
}
|
||||
|
||||
public ArgumentList getArgumentList()
|
||||
{
|
||||
Node actNode = getActionNode();
|
||||
int nArgNodes = actNode.getNNodes();
|
||||
ArgumentList argList = new ArgumentList();
|
||||
for (int n=0; n<nArgNodes; n++) {
|
||||
Argument arg = new Argument();
|
||||
Node argNode = actNode.getNode(n);
|
||||
arg.setName(argNode.getName());
|
||||
arg.setValue(argNode.getValue());
|
||||
argList.add(arg);
|
||||
}
|
||||
return argList;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// setRequest
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setRequest(Action action, ArgumentList argList)
|
||||
{
|
||||
Service service = action.getService();
|
||||
|
||||
setRequestHost(service);
|
||||
|
||||
setEnvelopeNode(SOAP.createEnvelopeBodyNode());
|
||||
Node envNode = getEnvelopeNode();
|
||||
Node bodyNode = getBodyNode();
|
||||
Node argNode = createContentNode(service, action, argList);
|
||||
bodyNode.addNode(argNode);
|
||||
setContent(envNode);
|
||||
|
||||
String serviceType = service.getServiceType();
|
||||
String actionName = action.getName();
|
||||
String soapAction = "\"" +
|
||||
serviceType +
|
||||
"#" + actionName +
|
||||
"\"";
|
||||
setSOAPAction(soapAction);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Contents
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node createContentNode(Service service, Action action, ArgumentList argList)
|
||||
{
|
||||
String actionName = action.getName();
|
||||
String serviceType = service.getServiceType();
|
||||
|
||||
Node actionNode = new Node();
|
||||
actionNode.setName(Control.NS, actionName);
|
||||
actionNode.setNameSpace(Control.NS, serviceType);
|
||||
|
||||
int argListCnt = argList.size();
|
||||
for (int n=0; n<argListCnt; n++) {
|
||||
Argument arg = argList.getArgument(n);
|
||||
Node argNode = new Node();
|
||||
argNode.setName(arg.getName());
|
||||
argNode.setValue(arg.getValue());
|
||||
actionNode.addNode(argNode);
|
||||
}
|
||||
|
||||
return actionNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ActionResponse post()
|
||||
{
|
||||
SOAPResponse soapRes = postMessage(getRequestHost(), getRequestPort());
|
||||
return new ActionResponse(soapRes);
|
||||
}
|
||||
}
|
||||
|
120
router/java/src/org/cybergarage/upnp/control/ActionResponse.java
Normal file
120
router/java/src/org/cybergarage/upnp/control/ActionResponse.java
Normal file
@ -0,0 +1,120 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ActionResponse.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
* 09/02/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : Action Responses do not contain the mandatory header field EXT
|
||||
* - Error : ActionResponse class does not set the EXT header
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.soap.*;
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class ActionResponse extends ControlResponse
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ActionResponse()
|
||||
{
|
||||
setHeader(HTTP.EXT, "");
|
||||
}
|
||||
|
||||
public ActionResponse(SOAPResponse soapRes)
|
||||
{
|
||||
super(soapRes);
|
||||
setHeader(HTTP.EXT, "");
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Response
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setResponse(Action action)
|
||||
{
|
||||
setStatusCode(HTTPStatus.OK);
|
||||
|
||||
Node bodyNode = getBodyNode();
|
||||
Node resNode = createResponseNode(action);
|
||||
bodyNode.addNode(resNode);
|
||||
|
||||
Node envNode = getEnvelopeNode();
|
||||
setContent(envNode);
|
||||
}
|
||||
|
||||
private Node createResponseNode(Action action)
|
||||
{
|
||||
String actionName = action.getName();
|
||||
Node actionNameResNode = new Node(SOAP.METHODNS + SOAP.DELIM + actionName + SOAP.RESPONSE);
|
||||
|
||||
Service service = action.getService();
|
||||
if (service != null) {
|
||||
actionNameResNode.setAttribute(
|
||||
"xmlns:" + SOAP.METHODNS,
|
||||
service.getServiceType());
|
||||
}
|
||||
|
||||
ArgumentList argList = action.getArgumentList();
|
||||
int nArgs = argList.size();
|
||||
for (int n=0; n<nArgs; n++) {
|
||||
Argument arg = argList.getArgument(n);
|
||||
if (arg.isOutDirection() == false)
|
||||
continue;
|
||||
Node argNode = new Node();
|
||||
argNode.setName(arg.getName());
|
||||
argNode.setValue(arg.getValue());
|
||||
actionNameResNode.addNode(argNode);
|
||||
}
|
||||
|
||||
return actionNameResNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// getResponse
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node getActionResponseNode()
|
||||
{
|
||||
Node bodyNode = getBodyNode();
|
||||
if (bodyNode == null || bodyNode.hasNodes() == false)
|
||||
return null;
|
||||
return bodyNode.getNode(0);
|
||||
}
|
||||
|
||||
|
||||
public ArgumentList getResponse()
|
||||
{
|
||||
ArgumentList argList = new ArgumentList();
|
||||
|
||||
Node resNode = getActionResponseNode();
|
||||
if (resNode == null)
|
||||
return argList;
|
||||
|
||||
int nArgs = resNode.getNNodes();
|
||||
for (int n=0; n<nArgs; n++) {
|
||||
Node node = resNode.getNode(n);
|
||||
String name = node.getName();
|
||||
String value = node.getValue();
|
||||
Argument arg = new Argument(name, value);
|
||||
argList.add(arg);
|
||||
}
|
||||
|
||||
return argList;
|
||||
}
|
||||
}
|
29
router/java/src/org/cybergarage/upnp/control/Control.java
Normal file
29
router/java/src/org/cybergarage/upnp/control/Control.java
Normal file
@ -0,0 +1,29 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: Control.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/20/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
public class Control
|
||||
{
|
||||
public final static String NS = "u";
|
||||
public final static String QUERY_SOAPACTION = "urn:schemas-upnp-org:control-1-0#QueryStateVariable";
|
||||
public final static String XMLNS = "urn:schemas-upnp-org:control-1-0";
|
||||
public final static String QUERY_STATE_VARIABLE = "QueryStateVariable";
|
||||
public final static String QUERY_STATE_VARIABLE_RESPONSE = "QueryStateVariableResponse";
|
||||
public final static String VAR_NAME = "varName";
|
||||
public final static String RETURN = "return";
|
||||
}
|
||||
|
||||
|
128
router/java/src/org/cybergarage/upnp/control/ControlRequest.java
Normal file
128
router/java/src/org/cybergarage/upnp/control/ControlRequest.java
Normal file
@ -0,0 +1,128 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ControlRequest.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
* 05/22/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Description: inserted a check at the beginning of the setRequestHost method
|
||||
* - Problem : If the host does not start with a '/', the device could refuse the control action
|
||||
* - Error : it is not an error, but adding the '/' when missing allows the integration with the Intel devices
|
||||
* 09/02/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it> / Suzan Foster
|
||||
* - Problem : NullpointerException thrown for devices whose description use absolute urls
|
||||
* - Error : the presence of a base url is not mandatory, the API code makes the assumption that control and event subscription urls are relative.
|
||||
* If the baseUrl is not present, the request host and port should be extracted from the control/subscription url
|
||||
* - Description: The method setRequestHost/setService should be changed as follows
|
||||
* 02/17/04
|
||||
* - Rob van den Boomen <rob.van.den.boomen@philips.com>
|
||||
* - Fixed to set a URLBase from the SSDP header when the URLBase of the description is null.
|
||||
* 02/18/04
|
||||
* - Andre <andre@antiheld.net>
|
||||
* - The xml nodes controlUrl and eventSubUrl can contain absolut urls, but these absolut urls may have
|
||||
* different ports than the base url! (so seen on my SMC 7004ABR Barricade Router, where xml files are
|
||||
* requested from port 80, but soap requests are made on port 5440). Therefore whenever a request is made,
|
||||
* the port specified by the controlUrl or eventSubUrl node should be used, else no response will be returned
|
||||
* (oddly, there was a response returned even on port 80, but with empty body tags. but the correct response
|
||||
* finally came from port 5440).
|
||||
* - Fixed to get the port from the control url when it is absolute.
|
||||
* 03/20/04
|
||||
* - Thanks for Thomas Schulz <tsroyale at users.sourceforge.net>
|
||||
* - Fixed setRequestHost() for Sony's UPnP stack when the URLBase has the path.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.soap.*;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class ControlRequest extends SOAPRequest
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ControlRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public ControlRequest(HTTPRequest httpReq)
|
||||
{
|
||||
set(httpReq);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Query
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean isQueryControl()
|
||||
{
|
||||
return isSOAPAction(Control.QUERY_SOAPACTION);
|
||||
}
|
||||
|
||||
public boolean isActionControl()
|
||||
{
|
||||
return !isQueryControl();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// setRequest
|
||||
////////////////////////////////////////////////
|
||||
|
||||
protected void setRequestHost(Service service)
|
||||
{
|
||||
String ctrlURL = service.getControlURL();
|
||||
|
||||
// Thanks for Thomas Schulz (2004/03/20)
|
||||
String urlBase = service.getRootDevice().getURLBase();
|
||||
if (urlBase != null && 0 < urlBase.length()){
|
||||
try {
|
||||
URL url = new URL(urlBase);
|
||||
String basePath = url.getPath();
|
||||
int baseLen = basePath.length();
|
||||
if (0 < baseLen) {
|
||||
if (1 < baseLen || (basePath.charAt(0) != '/'))
|
||||
ctrlURL = basePath + ctrlURL;
|
||||
}
|
||||
}
|
||||
catch (MalformedURLException e) {}
|
||||
}
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (05/21/03)
|
||||
setURI(ctrlURL, true);
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> and Suzan Foster (09/02/03)
|
||||
// Thanks for Andre <andre@antiheld.net> (02/18/04)
|
||||
String postURL = "";
|
||||
if (HTTP.isAbsoluteURL(ctrlURL) == true)
|
||||
postURL = ctrlURL;
|
||||
|
||||
if (postURL == null || postURL.length() <= 0)
|
||||
postURL = service.getRootDevice().getURLBase();
|
||||
|
||||
// Thanks for Rob van den Boomen <rob.van.den.boomen@philips.com> (02/17/04)
|
||||
// BUGFIX, set urlbase from location string if not set in description.xml
|
||||
if (postURL == null || postURL.length() <= 0)
|
||||
postURL = service.getRootDevice().getLocation();
|
||||
|
||||
String reqHost = HTTP.getHost(postURL);
|
||||
int reqPort = HTTP.getPort(postURL);
|
||||
|
||||
setHost(reqHost, reqPort);
|
||||
setRequestHost(reqHost);
|
||||
setRequestPort(reqPort);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,168 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: ControlResponse.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.soap.*;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class ControlResponse extends SOAPResponse
|
||||
{
|
||||
public static final String FAULT_CODE = "Client";
|
||||
public static final String FAULT_STRING = "UPnPError";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public ControlResponse()
|
||||
{
|
||||
setServer(UPnP.getServerName());
|
||||
}
|
||||
|
||||
public ControlResponse(SOAPResponse soapRes)
|
||||
{
|
||||
super(soapRes);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// FaultResponse
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setFaultResponse(int errCode, String errDescr)
|
||||
{
|
||||
setStatusCode(HTTPStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
Node bodyNode = getBodyNode();
|
||||
Node faultNode = createFaultResponseNode(errCode, errDescr);
|
||||
bodyNode.addNode(faultNode);
|
||||
|
||||
Node envNode = getEnvelopeNode();
|
||||
setContent(envNode);
|
||||
}
|
||||
|
||||
public void setFaultResponse(int errCode)
|
||||
{
|
||||
setFaultResponse(errCode, UPnPStatus.code2String(errCode));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// createFaultResponseNode
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node createFaultResponseNode(int errCode, String errDescr)
|
||||
{
|
||||
// <s:Fault>
|
||||
Node faultNode = new Node(SOAP.XMLNS + SOAP.DELIM + SOAP.FAULT);
|
||||
|
||||
// <faultcode>s:Client</faultcode>
|
||||
Node faultCodeNode = new Node(SOAP.FAULT_CODE);
|
||||
faultCodeNode.setValue(SOAP.XMLNS + SOAP.DELIM + FAULT_CODE);
|
||||
faultNode.addNode(faultCodeNode);
|
||||
|
||||
// <faultstring>UPnPError</faultstring>
|
||||
Node faultStringNode = new Node(SOAP.FAULT_STRING);
|
||||
faultStringNode.setValue(FAULT_STRING);
|
||||
faultNode.addNode(faultStringNode);
|
||||
|
||||
// <detail>
|
||||
Node detailNode = new Node(SOAP.DETAIL);
|
||||
faultNode.addNode(detailNode);
|
||||
|
||||
// <UPnPError xmlns="urn:schemas-upnp-org:control-1-0">
|
||||
Node upnpErrorNode = new Node(FAULT_STRING);
|
||||
upnpErrorNode.setAttribute("xmlns", Control.XMLNS);
|
||||
detailNode.addNode(upnpErrorNode);
|
||||
|
||||
// <errorCode>error code</errorCode>
|
||||
Node errorCodeNode = new Node(SOAP.ERROR_CODE);
|
||||
errorCodeNode.setValue(errCode);
|
||||
upnpErrorNode.addNode(errorCodeNode);
|
||||
|
||||
// <errorDescription>error string</errorDescription>
|
||||
Node errorDesctiprionNode = new Node(SOAP.ERROR_DESCRIPTION);
|
||||
errorDesctiprionNode.setValue(errDescr);
|
||||
upnpErrorNode.addNode(errorDesctiprionNode);
|
||||
|
||||
return faultNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// UPnP Error
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private UPnPStatus upnpErr = new UPnPStatus();
|
||||
|
||||
private Node getUPnPErrorNode()
|
||||
{
|
||||
Node detailNode = getFaultDetailNode();
|
||||
if (detailNode == null)
|
||||
return null;
|
||||
return detailNode.getNodeEndsWith(SOAP.UPNP_ERROR);
|
||||
}
|
||||
|
||||
private Node getUPnPErrorCodeNode()
|
||||
{
|
||||
Node errorNode = getUPnPErrorNode();
|
||||
if (errorNode == null)
|
||||
return null;
|
||||
return errorNode.getNodeEndsWith(SOAP.ERROR_CODE);
|
||||
}
|
||||
|
||||
private Node getUPnPErrorDescriptionNode()
|
||||
{
|
||||
Node errorNode = getUPnPErrorNode();
|
||||
if (errorNode == null)
|
||||
return null;
|
||||
return errorNode.getNodeEndsWith(SOAP.ERROR_DESCRIPTION);
|
||||
}
|
||||
|
||||
public int getUPnPErrorCode()
|
||||
{
|
||||
Node errorCodeNode = getUPnPErrorCodeNode();
|
||||
if (errorCodeNode == null)
|
||||
return -1;
|
||||
String errorCodeStr = errorCodeNode.getValue();
|
||||
try {
|
||||
return Integer.parseInt(errorCodeStr);
|
||||
}
|
||||
catch (Exception e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public String getUPnPErrorDescription()
|
||||
{
|
||||
Node errorDescNode = getUPnPErrorDescriptionNode();
|
||||
if (errorDescNode == null)
|
||||
return "";
|
||||
return errorDescNode.getValue();
|
||||
}
|
||||
|
||||
public UPnPStatus getUPnPError()
|
||||
{
|
||||
int code = 0;
|
||||
String desc = "";
|
||||
code = getUPnPErrorCode();
|
||||
desc = getUPnPErrorDescription();
|
||||
upnpErr.setCode(code);
|
||||
upnpErr.setDescription(desc);
|
||||
return upnpErr;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: QueryListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/30/03
|
||||
* - first revision.
|
||||
* 01/04/04
|
||||
* - Changed the interface.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public interface QueryListener
|
||||
{
|
||||
public boolean queryControlReceived(StateVariable stateVar);
|
||||
}
|
117
router/java/src/org/cybergarage/upnp/control/QueryRequest.java
Normal file
117
router/java/src/org/cybergarage/upnp/control/QueryRequest.java
Normal file
@ -0,0 +1,117 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: QueryRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
* 09/02/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Error : redundant code, the setRequest method in QueryRequest invokes setURI even if after a couple of rows setRequestHost is invoked
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.soap.*;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class QueryRequest extends ControlRequest
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public QueryRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public QueryRequest(HTTPRequest httpReq)
|
||||
{
|
||||
set(httpReq);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Qyery
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node getVarNameNode()
|
||||
{
|
||||
Node bodyNode = getBodyNode();
|
||||
if (bodyNode == null)
|
||||
return null;
|
||||
if (bodyNode.hasNodes() == false)
|
||||
return null;
|
||||
Node queryStateVarNode = bodyNode.getNode(0);
|
||||
if (queryStateVarNode == null)
|
||||
return null;
|
||||
if (queryStateVarNode.hasNodes() == false)
|
||||
return null;
|
||||
return queryStateVarNode.getNode(0);
|
||||
}
|
||||
|
||||
public String getVarName()
|
||||
{
|
||||
Node node = getVarNameNode();
|
||||
if (node == null)
|
||||
return "";
|
||||
return node.getValue();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// setRequest
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setRequest(StateVariable stateVar)
|
||||
{
|
||||
Service service = stateVar.getService();
|
||||
|
||||
setRequestHost(service);
|
||||
|
||||
setEnvelopeNode(SOAP.createEnvelopeBodyNode());
|
||||
Node envNode = getEnvelopeNode();
|
||||
Node bodyNode = getBodyNode();
|
||||
Node qeuryNode = createContentNode(stateVar);
|
||||
bodyNode.addNode(qeuryNode);
|
||||
setContent(envNode);
|
||||
|
||||
setSOAPAction(Control.QUERY_SOAPACTION);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Contents
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node createContentNode(StateVariable stateVar)
|
||||
{
|
||||
Node queryVarNode = new Node();
|
||||
queryVarNode.setName(Control.NS, Control.QUERY_STATE_VARIABLE);
|
||||
queryVarNode.setNameSpace(Control.NS, Control.XMLNS);
|
||||
|
||||
Node varNode = new Node();
|
||||
varNode.setName(Control.NS, Control.VAR_NAME);
|
||||
varNode.setValue(stateVar.getName());
|
||||
queryVarNode.addNode(varNode);
|
||||
|
||||
return queryVarNode;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public QueryResponse post()
|
||||
{
|
||||
SOAPResponse soapRes = postMessage(getRequestHost(), getRequestPort());
|
||||
return new QueryResponse(soapRes);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,97 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: QueryResponse.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/30/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.soap.*;
|
||||
import org.cybergarage.xml.*;
|
||||
|
||||
public class QueryResponse extends ControlResponse
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public QueryResponse()
|
||||
{
|
||||
}
|
||||
|
||||
public QueryResponse(SOAPResponse soapRes)
|
||||
{
|
||||
super(soapRes);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Qyery
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Node getReturnNode()
|
||||
{
|
||||
Node bodyNode = getBodyNode();
|
||||
if (bodyNode == null)
|
||||
return null;
|
||||
if (bodyNode.hasNodes() == false)
|
||||
return null;
|
||||
Node queryResNode = bodyNode.getNode(0);
|
||||
if (queryResNode == null)
|
||||
return null;
|
||||
if (queryResNode.hasNodes() == false)
|
||||
return null;
|
||||
return queryResNode.getNode(0);
|
||||
}
|
||||
|
||||
public String getReturnValue()
|
||||
{
|
||||
Node node = getReturnNode();
|
||||
if (node == null)
|
||||
return "";
|
||||
return node.getValue();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Response
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setResponse(StateVariable stateVar)
|
||||
{
|
||||
String var = stateVar.getValue();
|
||||
|
||||
setStatusCode(HTTPStatus.OK);
|
||||
|
||||
Node bodyNode = getBodyNode();
|
||||
Node resNode = createResponseNode(var);
|
||||
bodyNode.addNode(resNode);
|
||||
|
||||
Node envNodee = getEnvelopeNode();
|
||||
setContent(envNodee);
|
||||
|
||||
}
|
||||
|
||||
private Node createResponseNode(String var)
|
||||
{
|
||||
Node queryResNode = new Node();
|
||||
queryResNode.setName(Control.NS, Control.QUERY_STATE_VARIABLE_RESPONSE);
|
||||
queryResNode.setNameSpace(Control.NS, Control.XMLNS);
|
||||
|
||||
Node returnNode = new Node();
|
||||
returnNode.setName(Control.RETURN);
|
||||
returnNode.setValue(var);
|
||||
queryResNode.addNode(returnNode);
|
||||
|
||||
return queryResNode;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: RenewSubscriber.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 07/07/04
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.control;
|
||||
|
||||
import org.cybergarage.util.*;
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class RenewSubscriber extends ThreadCore
|
||||
{
|
||||
public final static long INTERVAL = 120;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public RenewSubscriber(ControlPoint ctrlp)
|
||||
{
|
||||
setControlPoint(ctrlp);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ControlPoint ctrlPoint;
|
||||
|
||||
public void setControlPoint(ControlPoint ctrlp)
|
||||
{
|
||||
ctrlPoint = ctrlp;
|
||||
}
|
||||
|
||||
public ControlPoint getControlPoint()
|
||||
{
|
||||
return ctrlPoint;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Thread
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void run()
|
||||
{
|
||||
ControlPoint ctrlp = getControlPoint();
|
||||
long renewInterval = INTERVAL * 1000;
|
||||
while (isRunnable() == true) {
|
||||
try {
|
||||
Thread.sleep(renewInterval);
|
||||
} catch (InterruptedException e) {}
|
||||
ctrlp.renewSubscriberService();
|
||||
}
|
||||
}
|
||||
}
|
68
router/java/src/org/cybergarage/upnp/device/Advertiser.java
Normal file
68
router/java/src/org/cybergarage/upnp/device/Advertiser.java
Normal file
@ -0,0 +1,68 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: Advertiser.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/24/03
|
||||
* - first revision.
|
||||
* 06/18/04
|
||||
* - Changed to advertise every 25%-50% of the periodic notification cycle for NMPR;
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import org.cybergarage.util.*;
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class Advertiser extends ThreadCore
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Advertiser(Device dev)
|
||||
{
|
||||
setDevice(dev);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Device device;
|
||||
|
||||
public void setDevice(Device dev)
|
||||
{
|
||||
device = dev;
|
||||
}
|
||||
|
||||
public Device getDevice()
|
||||
{
|
||||
return device;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Thread
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void run()
|
||||
{
|
||||
Device dev = getDevice();
|
||||
long leaseTime = dev.getLeaseTime();
|
||||
long notifyInterval;
|
||||
while (isRunnable() == true) {
|
||||
notifyInterval = (leaseTime/4) + (long)((float)leaseTime * (Math.random() * 0.25f));
|
||||
notifyInterval *= 1000;
|
||||
try {
|
||||
Thread.sleep(notifyInterval);
|
||||
} catch (InterruptedException e) {}
|
||||
dev.announce();
|
||||
}
|
||||
}
|
||||
}
|
24
router/java/src/org/cybergarage/upnp/device/Description.java
Normal file
24
router/java/src/org/cybergarage/upnp/device/Description.java
Normal file
@ -0,0 +1,24 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: MAN.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/30/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
public class Description
|
||||
{
|
||||
public final static String LOADING_EXCEPTION = "Couldn't load a specified description file ";
|
||||
public final static String NOROOT_EXCEPTION = "Couldn't find a root node";
|
||||
public final static String NOROOTDEVICE_EXCEPTION = "Couldn't find a root device node";
|
||||
}
|
||||
|
@ -0,0 +1,27 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: DeviceChangeListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 09/12/04
|
||||
* - Oliver Newell <newell@media-rush.com>
|
||||
* - Added this class to allow ControlPoint applications to
|
||||
* be notified when the ControlPoint base class adds/removes
|
||||
* a UPnP device
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import org.cybergarage.upnp.Device;
|
||||
|
||||
public interface DeviceChangeListener
|
||||
{
|
||||
public void deviceAdded( Device dev );
|
||||
public void deviceRemoved( Device dev );
|
||||
}
|
66
router/java/src/org/cybergarage/upnp/device/Disposer.java
Normal file
66
router/java/src/org/cybergarage/upnp/device/Disposer.java
Normal file
@ -0,0 +1,66 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: Disposer.java
|
||||
*
|
||||
* Revision:
|
||||
*
|
||||
* 01/05/04
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class Disposer extends ThreadCore
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Disposer(ControlPoint ctrlp)
|
||||
{
|
||||
setControlPoint(ctrlp);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ControlPoint ctrlPoint;
|
||||
|
||||
public void setControlPoint(ControlPoint ctrlp)
|
||||
{
|
||||
ctrlPoint = ctrlp;
|
||||
}
|
||||
|
||||
public ControlPoint getControlPoint()
|
||||
{
|
||||
return ctrlPoint;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Thread
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void run()
|
||||
{
|
||||
Thread.currentThread().setName("UPnP-Disposer");
|
||||
ControlPoint ctrlp = getControlPoint();
|
||||
long monitorInterval = ctrlp.getExpiredDeviceMonitoringInterval() * 1000;
|
||||
|
||||
while (isRunnable() == true) {
|
||||
try {
|
||||
Thread.sleep(monitorInterval);
|
||||
} catch (InterruptedException e) {}
|
||||
ctrlp.removeExpiredDevices();
|
||||
//ctrlp.print();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: InvalidDescriptionException.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/26/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class InvalidDescriptionException extends Exception
|
||||
{
|
||||
private static final long serialVersionUID = -3144583349586910509L;
|
||||
|
||||
public InvalidDescriptionException()
|
||||
{
|
||||
super();
|
||||
}
|
||||
|
||||
public InvalidDescriptionException(String s)
|
||||
{
|
||||
super(s);
|
||||
}
|
||||
|
||||
public InvalidDescriptionException(String s, File file)
|
||||
{
|
||||
super(s + " (" + file.toString() + ")");
|
||||
}
|
||||
|
||||
public InvalidDescriptionException(Exception e)
|
||||
{
|
||||
super(e.getMessage());
|
||||
}
|
||||
}
|
31
router/java/src/org/cybergarage/upnp/device/MAN.java
Normal file
31
router/java/src/org/cybergarage/upnp/device/MAN.java
Normal file
@ -0,0 +1,31 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: MAN.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/30/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
public class MAN
|
||||
{
|
||||
public final static String DISCOVER = "ssdp:discover";
|
||||
|
||||
public final static boolean isDiscover(String value)
|
||||
{
|
||||
if (value == null)
|
||||
return false;
|
||||
if (value.equals(MAN.DISCOVER) == true)
|
||||
return true;
|
||||
return value.equals("\"" + MAN.DISCOVER + "\"");
|
||||
}
|
||||
}
|
||||
|
30
router/java/src/org/cybergarage/upnp/device/NT.java
Normal file
30
router/java/src/org/cybergarage/upnp/device/NT.java
Normal file
@ -0,0 +1,30 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: NT.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/09/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
public class NT
|
||||
{
|
||||
public final static String ROOTDEVICE = "upnp:rootdevice";
|
||||
public final static String EVENT = "upnp:event";
|
||||
|
||||
public final static boolean isRootDevice(String ntValue)
|
||||
{
|
||||
if (ntValue == null)
|
||||
return false;
|
||||
return ntValue.startsWith(ROOTDEVICE);
|
||||
}
|
||||
}
|
||||
|
38
router/java/src/org/cybergarage/upnp/device/NTS.java
Normal file
38
router/java/src/org/cybergarage/upnp/device/NTS.java
Normal file
@ -0,0 +1,38 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: NTS.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/09/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
public class NTS
|
||||
{
|
||||
public final static String ALIVE = "ssdp:alive";
|
||||
public final static String BYEBYE = "ssdp:byebye";
|
||||
public final static String PROPCHANGE = "upnp:propchange";
|
||||
|
||||
public final static boolean isAlive(String ntsValue)
|
||||
{
|
||||
if (ntsValue == null)
|
||||
return false;
|
||||
return ntsValue.startsWith(NTS.ALIVE);
|
||||
}
|
||||
|
||||
public final static boolean isByeBye(String ntsValue)
|
||||
{
|
||||
if (ntsValue == null)
|
||||
return false;
|
||||
return ntsValue.startsWith(NTS.BYEBYE);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,23 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: DeviceNotifyListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import org.cybergarage.upnp.ssdp.*;
|
||||
|
||||
public interface NotifyListener
|
||||
{
|
||||
public void deviceNotifyReceived(SSDPPacket ssdpPacket);
|
||||
}
|
71
router/java/src/org/cybergarage/upnp/device/ST.java
Normal file
71
router/java/src/org/cybergarage/upnp/device/ST.java
Normal file
@ -0,0 +1,71 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: ST.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/07/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
public class ST
|
||||
{
|
||||
public final static String ALL_DEVICE = "ssdp:all";
|
||||
public final static String ROOT_DEVICE = "upnp:rootdevice";
|
||||
public final static String UUID_DEVICE = "uuid";
|
||||
public final static String URN_DEVICE = "urn:schemas-upnp-org:device:";
|
||||
public final static String URN_SERVICE = "urn:schemas-upnp-org:service:";
|
||||
|
||||
public final static boolean isAllDevice(String value)
|
||||
{
|
||||
if (value == null)
|
||||
return false;
|
||||
if (value.equals(ALL_DEVICE) == true)
|
||||
return true;
|
||||
return value.equals("\"" + ALL_DEVICE + "\"");
|
||||
}
|
||||
|
||||
public final static boolean isRootDevice(String value)
|
||||
{
|
||||
if (value == null)
|
||||
return false;
|
||||
if (value.equals(ROOT_DEVICE) == true)
|
||||
return true;
|
||||
return value.equals("\"" + ROOT_DEVICE + "\"");
|
||||
}
|
||||
|
||||
public final static boolean isUUIDDevice(String value)
|
||||
{
|
||||
if (value == null)
|
||||
return false;
|
||||
if (value.startsWith(UUID_DEVICE) == true)
|
||||
return true;
|
||||
return value.startsWith("\"" + UUID_DEVICE);
|
||||
}
|
||||
|
||||
public final static boolean isURNDevice(String value)
|
||||
{
|
||||
if (value == null)
|
||||
return false;
|
||||
if (value.startsWith(URN_DEVICE) == true)
|
||||
return true;
|
||||
return value.startsWith("\"" + URN_DEVICE);
|
||||
}
|
||||
|
||||
public final static boolean isURNService(String value)
|
||||
{
|
||||
if (value == null)
|
||||
return false;
|
||||
if (value.startsWith(URN_SERVICE) == true)
|
||||
return true;
|
||||
return value.startsWith("\"" + URN_SERVICE);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,23 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SearchListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02b
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import org.cybergarage.upnp.ssdp.*;
|
||||
|
||||
public interface SearchListener
|
||||
{
|
||||
public void deviceSearchReceived(SSDPPacket ssdpPacket);
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SearchResponseListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
import org.cybergarage.upnp.ssdp.*;
|
||||
|
||||
public interface SearchResponseListener
|
||||
{
|
||||
public void deviceSearchResponseReceived(SSDPPacket ssdpPacket);
|
||||
}
|
40
router/java/src/org/cybergarage/upnp/device/USN.java
Normal file
40
router/java/src/org/cybergarage/upnp/device/USN.java
Normal file
@ -0,0 +1,40 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: USN.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/09/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.device;
|
||||
|
||||
public class USN
|
||||
{
|
||||
public final static String ROOTDEVICE = "upnp:rootdevice";
|
||||
|
||||
public final static boolean isRootDevice(String usnValue)
|
||||
{
|
||||
if (usnValue == null)
|
||||
return false;
|
||||
return usnValue.endsWith(ROOTDEVICE);
|
||||
}
|
||||
|
||||
public final static String getUDN(String usnValue)
|
||||
{
|
||||
if (usnValue == null)
|
||||
return "";
|
||||
int idx = usnValue.indexOf("::");
|
||||
if (idx < 0)
|
||||
return usnValue.trim();
|
||||
String udnValue = new String(usnValue.getBytes(), 0, idx);
|
||||
return udnValue.trim();
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,21 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: EventListener.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
public interface EventListener
|
||||
{
|
||||
public void eventNotifyReceived(String uuid, long seq, String varName, String value);
|
||||
}
|
187
router/java/src/org/cybergarage/upnp/event/NotifyRequest.java
Normal file
187
router/java/src/org/cybergarage/upnp/event/NotifyRequest.java
Normal file
@ -0,0 +1,187 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SOAPRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 12/11/02
|
||||
* - first revision.
|
||||
* 05/22/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Description: removed the xml namespace
|
||||
* - Problem : Notification messages refer to uncorrect variable names
|
||||
* - Error : The NotifyRequest class introduces the XML namespace in variable names, too
|
||||
* 05/22/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : Notification messages refer to uncorrect variable names
|
||||
* - Error : The NotifyRequest class introduces the XML namespace in variable names, too
|
||||
* - Description : removed the xml namespace
|
||||
* 09/03/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : Notification messages refer to uncorrect variable names
|
||||
* - Error : The NotifyRequest class introduces the XML namespace in variable names, too
|
||||
* - Description: removed the xml namespace
|
||||
* 09/08/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : when an event notification message is received and the message
|
||||
* contains updates on more than one variable, only the first variable update
|
||||
* is notified.
|
||||
* - Error : the other xml nodes of the message are ignored
|
||||
* - Fix : add two methods to the NotifyRequest for extracting the property array
|
||||
* and modify the httpRequestRecieved method in ControlPoint
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.xml.*;
|
||||
import org.cybergarage.soap.*;
|
||||
|
||||
import org.cybergarage.upnp.device.*;
|
||||
|
||||
public class NotifyRequest extends SOAPRequest
|
||||
{
|
||||
private final static String XMLNS = "e";
|
||||
private final static String PROPERTY = "property";
|
||||
private final static String PROPERTYSET = "propertyset";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public NotifyRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public NotifyRequest(HTTPRequest httpReq)
|
||||
{
|
||||
set(httpReq);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// NT
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setNT(String value)
|
||||
{
|
||||
setHeader(HTTP.NT, value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// NTS
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setNTS(String value)
|
||||
{
|
||||
setHeader(HTTP.NTS, value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setSID(String id)
|
||||
{
|
||||
setHeader(HTTP.SID, Subscription.toSIDHeaderString(id));
|
||||
}
|
||||
|
||||
public String getSID()
|
||||
{
|
||||
return Subscription.getSID(getHeaderValue(HTTP.SID));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SEQ
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setSEQ(long value)
|
||||
{
|
||||
setHeader(HTTP.SEQ, Long.toString(value));
|
||||
}
|
||||
|
||||
public long getSEQ()
|
||||
{
|
||||
return getLongHeaderValue(HTTP.SEQ);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean setRequest(Subscriber sub, String varName, String value)
|
||||
{
|
||||
String sid = sub.getSID();
|
||||
long notifyCnt = sub.getNotifyCount();
|
||||
String host = sub.getDeliveryHost();
|
||||
String path = sub.getDeliveryPath();
|
||||
int port = sub.getDeliveryPort();
|
||||
|
||||
setMethod(HTTP.NOTIFY);
|
||||
setURI(path);
|
||||
setHost(host, port);
|
||||
setNT(NT.EVENT);
|
||||
setNTS(NTS.PROPCHANGE);
|
||||
setSID(sid);
|
||||
setSEQ(notifyCnt);
|
||||
|
||||
setContentType(XML.CONTENT_TYPE);
|
||||
Node propSetNode = createPropertySetNode(varName, value);
|
||||
setContent(propSetNode);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private Node createPropertySetNode(String varName, String value)
|
||||
{
|
||||
Node propSetNode = new Node(/*XMLNS + SOAP.DELIM + */PROPERTYSET);
|
||||
|
||||
propSetNode.setNameSpace(XMLNS, Subscription.XMLNS);
|
||||
|
||||
Node propNode = new Node(/*XMLNS + SOAP.DELIM + */PROPERTY);
|
||||
propSetNode.addNode(propNode);
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (05/22/03)
|
||||
//Node varNameNode = new Node(XMLNS + SOAP.DELIM + varName);
|
||||
Node varNameNode = new Node(varName);
|
||||
varNameNode.setValue(value);
|
||||
propNode.addNode(varNameNode);
|
||||
|
||||
return propSetNode;
|
||||
}
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/08/03)
|
||||
private Property getProperty(Node varNode)
|
||||
{
|
||||
Property prop = new Property();
|
||||
if (varNode == null)
|
||||
return prop;
|
||||
// remove the event namespace
|
||||
String variableName = varNode.getName();
|
||||
int index = variableName.lastIndexOf(':');
|
||||
if (index != -1)
|
||||
variableName = variableName.substring(index + 1);
|
||||
prop.setName(variableName);
|
||||
prop.setValue(varNode.getValue());
|
||||
return prop;
|
||||
}
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/08/03)
|
||||
public PropertyList getPropertyList() {
|
||||
PropertyList properties = new PropertyList();
|
||||
Node varSetNode = getEnvelopeNode();
|
||||
for (int i = 0; i<varSetNode.getNNodes(); i++){
|
||||
Node propNode = varSetNode.getNode(i);
|
||||
if (propNode == null)
|
||||
continue;
|
||||
Property prop = getProperty(propNode.getNode(0));
|
||||
properties.add(prop);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
}
|
65
router/java/src/org/cybergarage/upnp/event/Property.java
Normal file
65
router/java/src/org/cybergarage/upnp/event/Property.java
Normal file
@ -0,0 +1,65 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: Subscriber.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
* 05/22/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : the setName method does not set the name of the property
|
||||
* - Error : the method contains a bug:
|
||||
* 06/18/03
|
||||
* - Fixed a bug when a null value is received to the name and the value of property.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
public class Property
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Property()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// name
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String name = "";
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String val) {
|
||||
if (val == null)
|
||||
val = "";
|
||||
name = val;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// value
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String value = "";
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String val) {
|
||||
if (val == null)
|
||||
val = "";
|
||||
value = val;
|
||||
}
|
||||
}
|
46
router/java/src/org/cybergarage/upnp/event/PropertyList.java
Normal file
46
router/java/src/org/cybergarage/upnp/event/PropertyList.java
Normal file
@ -0,0 +1,46 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: PropertyList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 09/08/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class PropertyList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = 8718064210738306226L;
|
||||
public final static String ELEM_NAME = "PropertyList";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public PropertyList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Property getProperty(int n)
|
||||
{
|
||||
return (Property)get(n);
|
||||
}
|
||||
}
|
||||
|
180
router/java/src/org/cybergarage/upnp/event/Subscriber.java
Normal file
180
router/java/src/org/cybergarage/upnp/event/Subscriber.java
Normal file
@ -0,0 +1,180 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: Subscriber.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
* 07/31/04
|
||||
* - Added isExpired().
|
||||
* 10/26/04
|
||||
* - Oliver Newell <newell@media-rush.com>
|
||||
* - Added support the intinite time and fixed a bug in isExpired().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
public class Subscriber
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Subscriber()
|
||||
{
|
||||
renew();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String SID = null;
|
||||
|
||||
public String getSID() {
|
||||
return SID;
|
||||
}
|
||||
|
||||
public void setSID(String sid) {
|
||||
SID = sid;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// deliveryURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String ifAddr = "";
|
||||
|
||||
public void setInterfaceAddress(String addr)
|
||||
{
|
||||
ifAddr = addr;
|
||||
}
|
||||
|
||||
public String getInterfaceAddress()
|
||||
{
|
||||
return ifAddr;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// deliveryURL
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String deliveryURL = "";
|
||||
|
||||
public String getDeliveryURL() {
|
||||
return deliveryURL;
|
||||
}
|
||||
|
||||
public void setDeliveryURL(String deliveryURL) {
|
||||
this.deliveryURL = deliveryURL;
|
||||
try {
|
||||
URL url = new URL(deliveryURL);
|
||||
deliveryHost = url.getHost();
|
||||
deliveryPath = url.getPath();
|
||||
deliveryPort = url.getPort();
|
||||
}
|
||||
catch (Exception e) {}
|
||||
}
|
||||
|
||||
private String deliveryHost = "";
|
||||
private String deliveryPath = "";
|
||||
private int deliveryPort = 0;
|
||||
|
||||
public String getDeliveryHost() {
|
||||
return deliveryHost;
|
||||
}
|
||||
|
||||
public String getDeliveryPath() {
|
||||
return deliveryPath;
|
||||
}
|
||||
|
||||
public int getDeliveryPort() {
|
||||
return deliveryPort;
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Timeout
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private long timeOut = 0;
|
||||
|
||||
public long getTimeOut() {
|
||||
return timeOut;
|
||||
}
|
||||
|
||||
public void setTimeOut(long value) {
|
||||
timeOut = value;
|
||||
}
|
||||
|
||||
public boolean isExpired()
|
||||
{
|
||||
long currTime = System.currentTimeMillis();
|
||||
|
||||
// Thanks for Oliver Newell (10/26/04)
|
||||
if(timeOut == Subscription.INFINITE_VALUE )
|
||||
return false;
|
||||
|
||||
// Thanks for Oliver Newell (10/26/04)
|
||||
long expiredTime = getSubscriptionTime() + getTimeOut()*1000;
|
||||
if (expiredTime < currTime)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SubscriptionTIme
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private long subscriptionTime = 0;
|
||||
|
||||
public long getSubscriptionTime() {
|
||||
return subscriptionTime;
|
||||
}
|
||||
|
||||
public void setSubscriptionTime(long time) {
|
||||
subscriptionTime = time;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SEQ
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private long notifyCount = 0;
|
||||
|
||||
public long getNotifyCount() {
|
||||
return notifyCount;
|
||||
}
|
||||
|
||||
public void setNotifyCount(int cnt) {
|
||||
notifyCount = cnt;
|
||||
}
|
||||
|
||||
public void incrementNotifyCount() {
|
||||
if (notifyCount == Long.MAX_VALUE) {
|
||||
notifyCount = 1;
|
||||
return;
|
||||
}
|
||||
notifyCount++;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// renew
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void renew()
|
||||
{
|
||||
setSubscriptionTime(System.currentTimeMillis());
|
||||
setNotifyCount(0);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SubscriberList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/31/03
|
||||
* - first revision.
|
||||
* 06/18/03
|
||||
* - Fixed to catch ArrayIndexOutOfBounds.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class SubscriberList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = -648427977601494972L;
|
||||
|
||||
public SubscriberList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public Subscriber getSubscriber(int n)
|
||||
{
|
||||
Object obj = null;
|
||||
try {
|
||||
obj = get(n);
|
||||
}
|
||||
catch (Exception e) {}
|
||||
return (Subscriber)obj;
|
||||
}
|
||||
}
|
||||
|
75
router/java/src/org/cybergarage/upnp/event/Subscription.java
Normal file
75
router/java/src/org/cybergarage/upnp/event/Subscription.java
Normal file
@ -0,0 +1,75 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: ST.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/31/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class Subscription
|
||||
{
|
||||
public final static String XMLNS = "urn:schemas-upnp-org:event-1-0";
|
||||
public final static String TIMEOUT_HEADER = "Second-";
|
||||
public final static String INFINITE_STRING = "infinite";
|
||||
public final static int INFINITE_VALUE = -1;
|
||||
public final static String UUID = "uuid:";
|
||||
public final static String SUBSCRIBE_METHOD = "SUBSCRIBE";
|
||||
public final static String UNSUBSCRIBE_METHOD = "UNSUBSCRIBE";
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Timeout
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static String toTimeoutHeaderString(long time)
|
||||
{
|
||||
if (time == Subscription.INFINITE_VALUE)
|
||||
return Subscription.INFINITE_STRING;
|
||||
return Subscription.TIMEOUT_HEADER + Long.toString(time);
|
||||
}
|
||||
|
||||
public final static long getTimeout(String headerValue)
|
||||
{
|
||||
int minusIdx = headerValue.indexOf('-');
|
||||
long timeout = Subscription.INFINITE_VALUE;
|
||||
try {
|
||||
String timeoutStr = headerValue.substring(minusIdx+1, headerValue.length());
|
||||
timeout = Long.parseLong(timeoutStr);
|
||||
}
|
||||
catch (Exception e) {}
|
||||
return timeout;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static final String createSID()
|
||||
{
|
||||
return UPnP.createUUID();
|
||||
}
|
||||
|
||||
public final static String toSIDHeaderString(String id)
|
||||
{
|
||||
return Subscription.UUID + id;
|
||||
}
|
||||
|
||||
public final static String getSID(String headerValue)
|
||||
{
|
||||
if (headerValue == null)
|
||||
return "";
|
||||
return headerValue.substring(Subscription.UUID.length(), headerValue.length());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,221 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SubscriptionRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/31/03
|
||||
* - first revision.
|
||||
* 05/21/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Description: inserted a check at the beginning of the setService method
|
||||
* - Problem : If the EventSubURL does not start with a '/', the device could refuse event subscription
|
||||
* - Error : it is not an error, but adding the '/' when missing allows the integration with the Intel devices
|
||||
* 09/02/03
|
||||
* - Giordano Sassaroli <sassarol@cefriel.it>
|
||||
* - Problem : NullpointerException thrown for devices whose description use absolute urls
|
||||
* - Error : the presence of a base url is not mandatory, the API code makes the assumption that control and event subscription urls are relative. If the baseUrl is not present, the request host and port should be extracted from the control/subscription url
|
||||
* - Description: The method setRequestHost/setService should be changed as follows
|
||||
* 06/11/04
|
||||
* - Markus Thurner <markus.thurner@fh-hagenberg.at> (06/11/2004)
|
||||
* - Changed setServie() to get the host address from the SSDP Location field when the URLBase is null.
|
||||
* 12/06/04
|
||||
* - Grzegorz Lehmann <grzegorz.lehmann@dai-labor.de>
|
||||
* - Stefano Lenzi <kismet-sl@users.sourceforge.net>
|
||||
* - Fixed getSID() to loop between getSID() and hasSID();
|
||||
*
|
||||
********************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
import org.cybergarage.upnp.device.*;
|
||||
|
||||
public class SubscriptionRequest extends HTTPRequest
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SubscriptionRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public SubscriptionRequest(HTTPRequest httpReq)
|
||||
{
|
||||
set(httpReq);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// setRequest
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private void setService(Service service)
|
||||
{
|
||||
String eventSubURL = service.getEventSubURL();
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (05/21/03)
|
||||
setURI(eventSubURL, true);
|
||||
|
||||
String urlBaseStr = "";
|
||||
Device dev = service.getDevice();
|
||||
if (dev != null)
|
||||
urlBaseStr = dev.getURLBase();
|
||||
|
||||
if (urlBaseStr == null || urlBaseStr.length() <= 0) {
|
||||
Device rootDev = service.getRootDevice();
|
||||
if (rootDev != null)
|
||||
urlBaseStr = rootDev.getURLBase();
|
||||
}
|
||||
|
||||
// Thansk for Markus Thurner <markus.thurner@fh-hagenberg.at> (06/11/2004)
|
||||
if (urlBaseStr == null || urlBaseStr.length() <= 0) {
|
||||
Device rootDev = service.getRootDevice();
|
||||
if (rootDev != null)
|
||||
urlBaseStr = rootDev.getLocation();
|
||||
}
|
||||
|
||||
// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/02/03)
|
||||
if (urlBaseStr == null || urlBaseStr.length() <= 0) {
|
||||
if (HTTP.isAbsoluteURL(eventSubURL))
|
||||
urlBaseStr = eventSubURL;
|
||||
}
|
||||
|
||||
String reqHost = HTTP.getHost(urlBaseStr);
|
||||
int reqPort = HTTP.getPort(urlBaseStr);
|
||||
|
||||
setHost(reqHost, reqPort);
|
||||
setRequestHost(reqHost);
|
||||
setRequestPort(reqPort);
|
||||
}
|
||||
|
||||
public void setSubscribeRequest(Service service, String callback, long timeout)
|
||||
{
|
||||
setMethod(Subscription.SUBSCRIBE_METHOD);
|
||||
setService(service);
|
||||
setCallback(callback);
|
||||
setNT(NT.EVENT);
|
||||
setTimeout(timeout);
|
||||
}
|
||||
|
||||
public void setRenewRequest(Service service, String uuid, long timeout)
|
||||
{
|
||||
setMethod(Subscription.SUBSCRIBE_METHOD);
|
||||
setService(service);
|
||||
setSID(uuid);
|
||||
setTimeout(timeout);
|
||||
}
|
||||
|
||||
public void setUnsubscribeRequest(Service service)
|
||||
{
|
||||
setMethod(Subscription.UNSUBSCRIBE_METHOD);
|
||||
setService(service);
|
||||
setSID(service.getSID());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// NT
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setNT(String value)
|
||||
{
|
||||
setHeader(HTTP.NT, value);
|
||||
}
|
||||
|
||||
public String getNT()
|
||||
{
|
||||
return getHeaderValue(HTTP.NT);
|
||||
}
|
||||
|
||||
public boolean hasNT()
|
||||
{
|
||||
String nt = getNT();
|
||||
return (nt != null && 0 < nt.length()) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// CALLBACK
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private final static String CALLBACK_START_WITH = "<";
|
||||
private final static String CALLBACK_END_WITH = ">";
|
||||
|
||||
public void setCallback(String value)
|
||||
{
|
||||
setStringHeader(HTTP.CALLBACK, value, CALLBACK_START_WITH, CALLBACK_END_WITH);
|
||||
}
|
||||
|
||||
public String getCallback()
|
||||
{
|
||||
return getStringHeaderValue(HTTP.CALLBACK, CALLBACK_START_WITH, CALLBACK_END_WITH);
|
||||
}
|
||||
|
||||
public boolean hasCallback()
|
||||
{
|
||||
String callback = getCallback();
|
||||
return (callback != null && 0 < callback.length()) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setSID(String id)
|
||||
{
|
||||
setHeader(HTTP.SID, Subscription.toSIDHeaderString(id));
|
||||
}
|
||||
|
||||
public String getSID()
|
||||
{
|
||||
// Thanks for Grzegorz Lehmann and Stefano Lenzi(12/06/04)
|
||||
String sid = Subscription.getSID(getHeaderValue(HTTP.SID));
|
||||
if (sid == null)
|
||||
return "";
|
||||
return sid;
|
||||
}
|
||||
|
||||
public boolean hasSID()
|
||||
{
|
||||
String sid = getSID();
|
||||
return (sid != null && 0 < sid.length()) ? true : false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Timeout
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final void setTimeout(long value)
|
||||
{
|
||||
setHeader(HTTP.TIMEOUT, Subscription.toTimeoutHeaderString(value));
|
||||
}
|
||||
|
||||
public long getTimeout()
|
||||
{
|
||||
return Subscription.getTimeout(getHeaderValue(HTTP.TIMEOUT));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post (Response)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void post(SubscriptionResponse subRes)
|
||||
{
|
||||
super.post(subRes);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SubscriptionResponse post()
|
||||
{
|
||||
HTTPResponse httpRes = post(getRequestHost(), getRequestPort());
|
||||
return new SubscriptionResponse(httpRes);
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SubscriptionResponse.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/29/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.event;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
import org.cybergarage.http.*;
|
||||
|
||||
public class SubscriptionResponse extends HTTPResponse
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SubscriptionResponse()
|
||||
{
|
||||
setServer(UPnP.getServerName());
|
||||
}
|
||||
|
||||
public SubscriptionResponse(HTTPResponse httpRes)
|
||||
{
|
||||
super(httpRes);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Error
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setResponse(int code)
|
||||
{
|
||||
setStatusCode(code);
|
||||
setContentLength(0);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Error
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setErrorResponse(int code)
|
||||
{
|
||||
setStatusCode(code);
|
||||
setContentLength(0);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// SID
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setSID(String id)
|
||||
{
|
||||
setHeader(HTTP.SID, Subscription.toSIDHeaderString(id));
|
||||
}
|
||||
|
||||
public String getSID()
|
||||
{
|
||||
return Subscription.getSID(getHeaderValue(HTTP.SID));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Timeout
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setTimeout(long value)
|
||||
{
|
||||
setHeader(HTTP.TIMEOUT, Subscription.toTimeoutHeaderString(value));
|
||||
}
|
||||
|
||||
public long getTimeout()
|
||||
{
|
||||
return Subscription.getTimeout(getHeaderValue(HTTP.TIMEOUT));
|
||||
}
|
||||
}
|
198
router/java/src/org/cybergarage/upnp/ssdp/HTTPMUSocket.java
Normal file
198
router/java/src/org/cybergarage/upnp/ssdp/HTTPMUSocket.java
Normal file
@ -0,0 +1,198 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2004
|
||||
*
|
||||
* File: HTTPMU.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 09/03/03
|
||||
* - Changed to open the socket using setReuseAddress().
|
||||
* 12/10/03
|
||||
* - Fixed getLocalAddress() to return a valid interface address.
|
||||
* 02/28/04
|
||||
* - Added getMulticastInetAddress(), getMulticastAddress().
|
||||
* 11/19/04
|
||||
* - Theo Beisch <theo.beisch@gmx.de>
|
||||
* - Changed send() to set the TTL as 4.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class HTTPMUSocket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private InetSocketAddress ssdpMultiGroup = null;
|
||||
private MulticastSocket ssdpMultiSock = null;
|
||||
private NetworkInterface ssdpMultiIf = null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPMUSocket()
|
||||
{
|
||||
}
|
||||
|
||||
public HTTPMUSocket(String addr, int port, String bindAddr)
|
||||
{
|
||||
open(addr, port, bindAddr);
|
||||
}
|
||||
|
||||
protected void finalize()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// bindAddr
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getLocalAddress()
|
||||
{
|
||||
InetAddress mcastAddr = ssdpMultiGroup.getAddress();
|
||||
Enumeration addrs = ssdpMultiIf.getInetAddresses();
|
||||
while (addrs.hasMoreElements()) {
|
||||
InetAddress addr = (InetAddress)addrs.nextElement();
|
||||
if (mcastAddr instanceof Inet6Address && addr instanceof Inet6Address)
|
||||
return addr.getHostAddress();
|
||||
if (mcastAddr instanceof Inet4Address && addr instanceof Inet4Address)
|
||||
return addr.getHostAddress();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// MulticastAddr
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public InetAddress getMulticastInetAddress()
|
||||
{
|
||||
return ssdpMultiGroup.getAddress();
|
||||
}
|
||||
|
||||
public String getMulticastAddress()
|
||||
{
|
||||
return getMulticastInetAddress().getHostAddress();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// open/close
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean open(String addr, int port, String bindAddr)
|
||||
{
|
||||
try {
|
||||
ssdpMultiSock = new MulticastSocket(null);
|
||||
ssdpMultiSock.setReuseAddress(true);
|
||||
InetSocketAddress bindSockAddr = new InetSocketAddress(port);
|
||||
ssdpMultiSock.bind(bindSockAddr);
|
||||
ssdpMultiGroup = new InetSocketAddress(InetAddress.getByName(addr), port);
|
||||
ssdpMultiIf = NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddr));
|
||||
ssdpMultiSock.joinGroup(ssdpMultiGroup, ssdpMultiIf);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean close()
|
||||
{
|
||||
if (ssdpMultiSock == null)
|
||||
return true;
|
||||
|
||||
try {
|
||||
ssdpMultiSock.leaveGroup(ssdpMultiGroup, ssdpMultiIf);
|
||||
ssdpMultiSock = null;
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// send
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean send(String msg, String bindAddr, int bindPort)
|
||||
{
|
||||
try {
|
||||
MulticastSocket msock;
|
||||
if ((bindAddr) != null && (0 < bindPort)) {
|
||||
msock = new MulticastSocket(null);
|
||||
msock.bind(new InetSocketAddress(bindAddr, bindPort));
|
||||
}
|
||||
else
|
||||
msock = new MulticastSocket();
|
||||
DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), ssdpMultiGroup);
|
||||
// Thnaks for Tho Beisch (11/09/04)
|
||||
msock.setTimeToLive(4);
|
||||
msock.send(dgmPacket);
|
||||
msock.close();
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean send(String msg)
|
||||
{
|
||||
return send(msg, null, -1);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post (HTTPRequest)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean post(HTTPRequest req, String bindAddr, int bindPort)
|
||||
{
|
||||
return send(req.toString(), bindAddr, bindPort);
|
||||
}
|
||||
|
||||
public boolean post(HTTPRequest req)
|
||||
{
|
||||
return send(req.toString(), null, -1);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// reveive
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SSDPPacket receive()
|
||||
{
|
||||
byte ssdvRecvBuf[] = new byte[SSDP.RECV_MESSAGE_BUFSIZE];
|
||||
SSDPPacket recvPacket = new SSDPPacket(ssdvRecvBuf, ssdvRecvBuf.length);
|
||||
recvPacket.setLocalAddress(getLocalAddress());
|
||||
try {
|
||||
ssdpMultiSock.receive(recvPacket.getDatagramPacket());
|
||||
recvPacket.setTimeStamp(System.currentTimeMillis());
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
}
|
||||
return recvPacket;
|
||||
}
|
||||
}
|
||||
|
239
router/java/src/org/cybergarage/upnp/ssdp/HTTPUSocket.java
Normal file
239
router/java/src/org/cybergarage/upnp/ssdp/HTTPUSocket.java
Normal file
@ -0,0 +1,239 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTTPMU.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/20/02
|
||||
* - first revision.
|
||||
* 12/12/03
|
||||
* - Inma Mar?n <inma@DIF.UM.ES>
|
||||
* - Changed open(addr, port) to send IPv6 SSDP packets.
|
||||
* - The socket binds only the port without the interface address.
|
||||
* - The full binding socket can send SSDP IPv4 packets. Is it a bug of J2SE v.1.4.2-b28 ?.
|
||||
* 01/06/04
|
||||
* - Oliver Newell <olivern@users.sourceforge.net>
|
||||
* - Added to set a current timestamp when the packet are received.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
import org.cybergarage.util.*;
|
||||
|
||||
public class HTTPUSocket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Member
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private DatagramSocket ssdpUniSock = null;
|
||||
//private MulticastSocket ssdpUniSock = null;
|
||||
|
||||
public DatagramSocket getDatagramSocket()
|
||||
{
|
||||
return ssdpUniSock;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public HTTPUSocket()
|
||||
{
|
||||
open();
|
||||
}
|
||||
|
||||
public HTTPUSocket(String bindAddr, int bindPort)
|
||||
{
|
||||
open(bindAddr, bindPort);
|
||||
}
|
||||
|
||||
public HTTPUSocket(int bindPort)
|
||||
{
|
||||
open(bindPort);
|
||||
}
|
||||
|
||||
protected void finalize()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// bindAddr
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String localAddr = "";
|
||||
|
||||
public void setLocalAddress(String addr)
|
||||
{
|
||||
localAddr = addr;
|
||||
}
|
||||
|
||||
public String getLocalAddress()
|
||||
{
|
||||
if (0 < localAddr.length())
|
||||
return localAddr;
|
||||
return ssdpUniSock.getLocalAddress().getHostAddress();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// open
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean open()
|
||||
{
|
||||
close();
|
||||
|
||||
try {
|
||||
ssdpUniSock = new DatagramSocket();
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean open(String bindAddr, int bindPort)
|
||||
{
|
||||
close();
|
||||
|
||||
try {
|
||||
// Bind only using the port without the interface address. (2003/12/12)
|
||||
InetSocketAddress bindSock = new InetSocketAddress(/*InetAddress.getByName(bindAddr), */ bindPort);
|
||||
ssdpUniSock = new DatagramSocket(null);
|
||||
ssdpUniSock.setReuseAddress(true);
|
||||
ssdpUniSock.bind(bindSock);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
setLocalAddress(bindAddr);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean open(int bindPort)
|
||||
{
|
||||
close();
|
||||
|
||||
try {
|
||||
InetSocketAddress bindSock = new InetSocketAddress(bindPort);
|
||||
ssdpUniSock = new DatagramSocket(null);
|
||||
ssdpUniSock.setReuseAddress(true);
|
||||
ssdpUniSock.bind(bindSock);
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// close
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean close()
|
||||
{
|
||||
if (ssdpUniSock == null)
|
||||
return true;
|
||||
|
||||
try {
|
||||
ssdpUniSock.close();
|
||||
ssdpUniSock = null;
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// send
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean post(String addr, int port, String msg)
|
||||
{
|
||||
try {
|
||||
InetAddress inetAddr = InetAddress.getByName(addr);
|
||||
DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port);
|
||||
ssdpUniSock.send(dgmPacket);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning("addr = " +ssdpUniSock.getLocalAddress().getHostName());
|
||||
Debug.warning("port = " + ssdpUniSock.getLocalPort());
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// reveive
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SSDPPacket receive()
|
||||
{
|
||||
byte ssdvRecvBuf[] = new byte[SSDP.RECV_MESSAGE_BUFSIZE];
|
||||
SSDPPacket recvPacket = new SSDPPacket(ssdvRecvBuf, ssdvRecvBuf.length);
|
||||
recvPacket.setLocalAddress(getLocalAddress());
|
||||
try {
|
||||
ssdpUniSock.receive(recvPacket.getDatagramPacket());
|
||||
recvPacket.setTimeStamp(System.currentTimeMillis());
|
||||
}
|
||||
catch (Exception e) {
|
||||
//Debug.warning(e);
|
||||
return null;
|
||||
}
|
||||
return recvPacket;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// join/leave
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/*
|
||||
boolean joinGroup(String mcastAddr, int mcastPort, String bindAddr)
|
||||
{
|
||||
try {
|
||||
InetSocketAddress mcastGroup = new InetSocketAddress(InetAddress.getByName(mcastAddr), mcastPort);
|
||||
NetworkInterface mcastIf = NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddr));
|
||||
ssdpUniSock.joinGroup(mcastGroup, mcastIf);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean leaveGroup(String mcastAddr, int mcastPort, String bindAddr)
|
||||
{
|
||||
try {
|
||||
InetSocketAddress mcastGroup = new InetSocketAddress(InetAddress.getByName(mcastAddr), mcastPort);
|
||||
NetworkInterface mcastIf = NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddr));
|
||||
ssdpUniSock.leaveGroup(mcastGroup, mcastIf);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.warning(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
77
router/java/src/org/cybergarage/upnp/ssdp/SSDP.java
Normal file
77
router/java/src/org/cybergarage/upnp/ssdp/SSDP.java
Normal file
@ -0,0 +1,77 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SSDP.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 05/13/03
|
||||
* - Added constants for IPv6.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
public class SSDP
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constants
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public static final int PORT = 1900;
|
||||
|
||||
public static final String ADDRESS = "239.255.255.250";
|
||||
|
||||
public static final String IPV6_LINK_LOCAL_ADDRESS = "FF02::C";
|
||||
public static final String IPV6_SUBNET_ADDRESS = "FF03::C";
|
||||
public static final String IPV6_ADMINISTRATIVE_ADDRESS = "FF04::C";
|
||||
public static final String IPV6_SITE_LOCAL_ADDRESS = "FF05::C";
|
||||
public static final String IPV6_GLOBAL_ADDRESS = "FF0E::C";
|
||||
|
||||
private static String IPV6_ADDRESS;
|
||||
|
||||
public static final void setIPv6Address(String addr)
|
||||
{
|
||||
IPV6_ADDRESS = addr;
|
||||
}
|
||||
|
||||
public static final String getIPv6Address()
|
||||
{
|
||||
return IPV6_ADDRESS;
|
||||
}
|
||||
|
||||
public static final int DEFAULT_MSEARCH_MX = 3;
|
||||
|
||||
public static final int RECV_MESSAGE_BUFSIZE = 1024;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Initialize
|
||||
////////////////////////////////////////////////
|
||||
|
||||
static
|
||||
{
|
||||
setIPv6Address(IPV6_LINK_LOCAL_ADDRESS);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// LeaseTime
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public final static int getLeaseTime(String cacheCont)
|
||||
{
|
||||
int equIdx = cacheCont.indexOf('=');
|
||||
int mx = 0;
|
||||
try {
|
||||
String mxStr = new String(cacheCont.getBytes(), equIdx+1, cacheCont.length() - (equIdx+1));
|
||||
mx = Integer.parseInt(mxStr);
|
||||
}
|
||||
catch (Exception e) {}
|
||||
return mx;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,31 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002
|
||||
*
|
||||
* File: SSDPMSearchRequest.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 01/14/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
|
||||
public class SSDPNotifyRequest extends SSDPRequest
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SSDPNotifyRequest()
|
||||
{
|
||||
setMethod(HTTP.NOTIFY);
|
||||
setURI("*");
|
||||
}
|
||||
}
|
132
router/java/src/org/cybergarage/upnp/ssdp/SSDPNotifySocket.java
Normal file
132
router/java/src/org/cybergarage/upnp/ssdp/SSDPNotifySocket.java
Normal file
@ -0,0 +1,132 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: SSDPNotifySocket.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/20/02
|
||||
* - first revision.
|
||||
* 05/13/03
|
||||
* - Added support for IPv6.
|
||||
* 02/20/04
|
||||
* - Inma Marin Lopez <inma@dif.um.es>
|
||||
* - Added a multicast filter using the SSDP pakcet.
|
||||
* 04/20/05
|
||||
* - Mikael Hakman <mhakman@dkab.net>
|
||||
* - Handle receive() returning null.
|
||||
* - Added close() in stop().
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
import org.cybergarage.net.*;
|
||||
import org.cybergarage.util.*;
|
||||
import org.cybergarage.http.*;
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class SSDPNotifySocket extends HTTPMUSocket implements Runnable
|
||||
{
|
||||
private boolean useIPv6Address;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SSDPNotifySocket(String bindAddr)
|
||||
{
|
||||
String addr = SSDP.ADDRESS;
|
||||
useIPv6Address = false;
|
||||
if (HostInterface.isIPv6Address(bindAddr) == true) {
|
||||
addr = SSDP.getIPv6Address();
|
||||
useIPv6Address = true;
|
||||
}
|
||||
open(addr, SSDP.PORT, bindAddr);
|
||||
setControlPoint(null);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ControlPoint
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private ControlPoint controlPoint = null;
|
||||
|
||||
public void setControlPoint(ControlPoint ctrlp)
|
||||
{
|
||||
this.controlPoint = ctrlp;
|
||||
}
|
||||
|
||||
public ControlPoint getControlPoint()
|
||||
{
|
||||
return controlPoint;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// post (SSDPNotifySocket)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean post(SSDPNotifyRequest req)
|
||||
{
|
||||
String ssdpAddr = SSDP.ADDRESS;
|
||||
if (useIPv6Address == true)
|
||||
ssdpAddr = SSDP.getIPv6Address();
|
||||
req.setHost(ssdpAddr, SSDP.PORT);
|
||||
return post((HTTPRequest)req);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// run
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private Thread deviceNotifyThread = null;
|
||||
|
||||
public void run()
|
||||
{
|
||||
Thread thisThread = Thread.currentThread();
|
||||
|
||||
ControlPoint ctrlPoint = getControlPoint();
|
||||
|
||||
while (deviceNotifyThread == thisThread) {
|
||||
Thread.yield();
|
||||
SSDPPacket packet = receive();
|
||||
|
||||
// Thanks for Mikael Hakman (04/20/05)
|
||||
if (packet == null)
|
||||
continue;
|
||||
|
||||
// Thanks for Inma (02/20/04)
|
||||
InetAddress maddr = getMulticastInetAddress();
|
||||
InetAddress pmaddr = packet.getHostInetAddress();
|
||||
if (maddr.equals(pmaddr) == false) {
|
||||
// I2P
|
||||
//Debug.warning("Invalidate Multicast Recieved : " + maddr + "," + pmaddr);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ctrlPoint != null)
|
||||
ctrlPoint.notifyReceived(packet);
|
||||
}
|
||||
}
|
||||
|
||||
public void start()
|
||||
{
|
||||
deviceNotifyThread = new Thread(this, "UPnP-SSDPNotifySocket");
|
||||
deviceNotifyThread.setDaemon(true);
|
||||
deviceNotifyThread.start();
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
// Thanks for Mikael Hakman (04/20/05)
|
||||
close();
|
||||
|
||||
deviceNotifyThread = null;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,106 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberUPnP for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: HTTPServerList.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 05/11/03
|
||||
* - first revision.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.cybergarage.net.*;
|
||||
|
||||
import org.cybergarage.upnp.*;
|
||||
|
||||
public class SSDPNotifySocketList extends Vector
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private static final long serialVersionUID = -7066290881503106399L;
|
||||
|
||||
public SSDPNotifySocketList()
|
||||
{
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SSDPNotifySocket getSSDPNotifySocket(int n)
|
||||
{
|
||||
return (SSDPNotifySocket)get(n);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// ControlPoint
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void setControlPoint(ControlPoint ctrlPoint)
|
||||
{
|
||||
int nSockets = size();
|
||||
for (int n=0; n<nSockets; n++) {
|
||||
SSDPNotifySocket sock = getSSDPNotifySocket(n);
|
||||
sock.setControlPoint(ctrlPoint);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean open()
|
||||
{
|
||||
int nHostAddrs = HostInterface.getNHostAddresses();
|
||||
for (int n=0; n<nHostAddrs; n++) {
|
||||
String bindAddr = HostInterface.getHostAddress(n);
|
||||
SSDPNotifySocket ssdpNotifySocket = new SSDPNotifySocket(bindAddr);
|
||||
add(ssdpNotifySocket);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void close()
|
||||
{
|
||||
int nSockets = size();
|
||||
for (int n=0; n<nSockets; n++) {
|
||||
SSDPNotifySocket sock = getSSDPNotifySocket(n);
|
||||
sock.close();
|
||||
}
|
||||
clear();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public void start()
|
||||
{
|
||||
int nSockets = size();
|
||||
for (int n=0; n<nSockets; n++) {
|
||||
SSDPNotifySocket sock = getSSDPNotifySocket(n);
|
||||
sock.start();
|
||||
}
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
int nSockets = size();
|
||||
for (int n=0; n<nSockets; n++) {
|
||||
SSDPNotifySocket sock = getSSDPNotifySocket(n);
|
||||
sock.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
243
router/java/src/org/cybergarage/upnp/ssdp/SSDPPacket.java
Normal file
243
router/java/src/org/cybergarage/upnp/ssdp/SSDPPacket.java
Normal file
@ -0,0 +1,243 @@
|
||||
/******************************************************************
|
||||
*
|
||||
* CyberLink for Java
|
||||
*
|
||||
* Copyright (C) Satoshi Konno 2002-2003
|
||||
*
|
||||
* File: SSDPPacket.java
|
||||
*
|
||||
* Revision;
|
||||
*
|
||||
* 11/18/02
|
||||
* - first revision.
|
||||
* 05/13/03
|
||||
* - Added getLocalAddress().
|
||||
* 11/01/04
|
||||
* - Theo Beisch <theo.beisch@gmx.de>
|
||||
* - Fixed isRootDevice() to check the ST header.
|
||||
* 11/19/04
|
||||
* - Theo Beisch <theo.beisch@gmx.de>
|
||||
* - Changed getRemoteAddress() to return the adresss instead of the host name.
|
||||
*
|
||||
******************************************************************/
|
||||
|
||||
package org.cybergarage.upnp.ssdp;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
import org.cybergarage.http.*;
|
||||
|
||||
import org.cybergarage.upnp.device.*;
|
||||
|
||||
public class SSDPPacket
|
||||
{
|
||||
////////////////////////////////////////////////
|
||||
// Constructor
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public SSDPPacket(byte[] buf, int length)
|
||||
{
|
||||
dgmPacket = new DatagramPacket(buf, length);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// DatagramPacket
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private DatagramPacket dgmPacket = null;
|
||||
|
||||
public DatagramPacket getDatagramPacket()
|
||||
{
|
||||
return dgmPacket;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// addr
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private String localAddr = "";
|
||||
|
||||
public void setLocalAddress(String addr)
|
||||
{
|
||||
localAddr = addr;
|
||||
}
|
||||
|
||||
public String getLocalAddress()
|
||||
{
|
||||
return localAddr;
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Time
|
||||
////////////////////////////////////////////////
|
||||
|
||||
private long timeStamp;
|
||||
|
||||
public void setTimeStamp(long value)
|
||||
{
|
||||
timeStamp = value;
|
||||
}
|
||||
|
||||
public long getTimeStamp()
|
||||
{
|
||||
return timeStamp;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Remote host
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public InetAddress getRemoteInetAddress()
|
||||
{
|
||||
return getDatagramPacket().getAddress();
|
||||
}
|
||||
|
||||
public String getRemoteAddress()
|
||||
{
|
||||
// Thanks for Theo Beisch (11/09/04)
|
||||
return getDatagramPacket().getAddress().getHostAddress();
|
||||
}
|
||||
|
||||
public int getRemotePort()
|
||||
{
|
||||
return getDatagramPacket().getPort();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Access Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public byte[] packetBytes = null;
|
||||
|
||||
public byte[] getData()
|
||||
{
|
||||
if (packetBytes != null)
|
||||
return packetBytes;
|
||||
|
||||
DatagramPacket packet = getDatagramPacket();
|
||||
int packetLen = packet.getLength();
|
||||
String packetData = new String(packet.getData(), 0, packetLen);
|
||||
packetBytes = packetData.getBytes();
|
||||
|
||||
return packetBytes;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Access Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String getHost()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.HOST);
|
||||
}
|
||||
|
||||
public String getCacheControl()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.CACHE_CONTROL);
|
||||
}
|
||||
|
||||
public String getLocation()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.LOCATION);
|
||||
}
|
||||
|
||||
public String getMAN()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.MAN);
|
||||
}
|
||||
|
||||
public String getST()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.ST);
|
||||
}
|
||||
|
||||
public String getNT()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.NT);
|
||||
}
|
||||
|
||||
public String getNTS()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.NTS);
|
||||
}
|
||||
|
||||
public String getServer()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.SERVER);
|
||||
}
|
||||
|
||||
public String getUSN()
|
||||
{
|
||||
return HTTPHeader.getValue(getData(), HTTP.USN);
|
||||
}
|
||||
|
||||
public int getMX()
|
||||
{
|
||||
return HTTPHeader.getIntegerValue(getData(), HTTP.MX);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Access Methods
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public InetAddress getHostInetAddress()
|
||||
{
|
||||
String addrStr = "127.0.0.1";
|
||||
String host = getHost();
|
||||
int canmaIdx = host.lastIndexOf(":");
|
||||
if (0 <= canmaIdx) {
|
||||
addrStr = host.substring(0, canmaIdx);
|
||||
if (addrStr.charAt(0) == '[')
|
||||
addrStr = addrStr.substring(1, addrStr.length());
|
||||
if (addrStr.charAt(addrStr.length()-1) == ']')
|
||||
addrStr = addrStr.substring(0, addrStr.length()-1);
|
||||
}
|
||||
InetSocketAddress isockaddr = new InetSocketAddress(addrStr, 0);
|
||||
return isockaddr.getAddress();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// Access Methods (Extension)
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public boolean isRootDevice()
|
||||
{
|
||||
if (NT.isRootDevice(getNT()) == true)
|
||||
return true;
|
||||
// Thanks for Theo Beisch (11/01/04)
|
||||
if (ST.isRootDevice(getST()) == true)
|
||||
return true;
|
||||
return USN.isRootDevice(getUSN());
|
||||
}
|
||||
|
||||
public boolean isDiscover()
|
||||
{
|
||||
return MAN.isDiscover(getMAN());
|
||||
}
|
||||
|
||||
public boolean isAlive()
|
||||
{
|
||||
return NTS.isAlive(getNTS());
|
||||
}
|
||||
|
||||
public boolean isByeBye()
|
||||
{
|
||||
return NTS.isByeBye(getNTS());
|
||||
}
|
||||
|
||||
public int getLeaseTime()
|
||||
{
|
||||
return SSDP.getLeaseTime(getCacheControl());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// toString
|
||||
////////////////////////////////////////////////
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return new String(getData());
|
||||
}
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user