Added support for starting a dummy router.

Added support for detecting whether I2PControl is run from a .jar (via RouterConsole).
Revised build.xml to include new libraries and remove old libraries.
Refactored NetworkInfo and changed name inte NetworkSetting.
This commit is contained in:
dev
2011-07-08 09:48:37 +00:00
parent 48d1ff2915
commit 3fa499b198
18 changed files with 890 additions and 33 deletions

View File

@ -6,5 +6,6 @@
<classpathentry kind="lib" path="/home/hottuna/Apps/i2p/lib/org.mortbay.jetty.jar"/>
<classpathentry kind="lib" path="/home/hottuna/Apps/i2p/lib/javax.servlet.jar"/>
<classpathentry kind="lib" path="/home/hottuna/Apps/i2p/lib/commons-logging.jar"/>
<classpathentry kind="lib" path="/home/hottuna/Apps/i2p/lib/router.jar"/>
<classpathentry kind="output" path="build/obj"/>
</classpath>

View File

@ -7,6 +7,7 @@
<path id="cp">
<pathelement path="${java.class.path}" />
<pathelement location="${i2plib}/i2p.jar" />
<pathelement location="${i2plib}/router.jar" />
<pathelement location="${i2plib}/i2ptunnel.jar" />
<pathelement location="${jettylib}/ant.jar"/>
<pathelement location="${jettylib}/org.mortbay.jetty.jar"/>
@ -15,6 +16,8 @@
<pathelement location="${jettylib}/javax.servlet.jar" />
<pathelement location="${jettylib}/commons-logging.jar" />
<pathelement location="${jettylib}/commons-el.jar" />
<pathelement location="${jettylib}/javax.servlet.jar" />
<pathelement location="${i2plib}/org.mortbay.jetty.jar" />
</path>
<target name="all" depends="clean, build" />
@ -31,8 +34,9 @@
srcdir="./java"
debug="true" deprecation="on" source="1.5" target="1.5"
destdir="./build/obj"
classpath="${i2plib}/i2p.jar:${jettylib}/javax.servlet.jar:${i2plib}/org.mortbay.jetty.jar" >
classpath="${cp}" >
<compilerarg line="${javac.compilerargs}" />
<classpath refid="cp"/>
</javac>
</target>

View File

@ -23,9 +23,11 @@ import java.util.Calendar;
import java.util.logging.LogManager;
import net.i2p.I2PAppContext;
import net.i2p.i2pcontrol.router.RouterManager;
import net.i2p.i2pcontrol.security.KeyStoreInitializer;
import net.i2p.i2pcontrol.security.SecurityManager;
import net.i2p.i2pcontrol.servlets.configuration.ConfigurationManager;
import net.i2p.i2pcontrol.util.IsJar;
import net.i2p.util.Log;
import org.mortbay.http.SslListener;
@ -68,16 +70,24 @@ public class I2PControlController{
//File pluginDir = new File(args[1]);
//if (!pluginDir.exists())
// throw new IllegalArgumentException("Plugin directory " + pluginDir.getAbsolutePath() + " does not exist");
I2PAppContext.getGlobalContext().logManager().setDefaultLimit(Log.STR_DEBUG);
// Enables devtime settings
if (!IsJar.isRunningJar()){
System.out.println("Running from non-jar");
_conf.getConf("i2pcontrol.listen.address", "127.0.0.1");
_conf.getConf("i2p.listen.port", 5555);
I2PAppContext.getGlobalContext().logManager().setDefaultLimit(Log.STR_DEBUG);
}
_server = new Server();
try {
SslListener ssl = new SslListener();
ssl.setProvider(SecurityManager.getSecurityProvider());
ssl.setCipherSuites(SecurityManager.getSupprtedSSLCipherSuites());
// FIXME: Change to use new ConrigurationManager.
ssl.setInetAddrPort(new InetAddrPort(Settings.getListenIP(), Settings.getListenPort()));
ssl.setWantClientAuth(false); // Don't care about client authetication.
ssl.setInetAddrPort(new InetAddrPort(
_conf.getConf("i2pcontrol.listen.address", "127.0.0.1"),
_conf.getConf("i2p.listen.port", 7560)));
ssl.setWantClientAuth(false); // Don't care about client authentication.
ssl.setPassword(SecurityManager.getKeyStorePassword());
ssl.setKeyPassword(SecurityManager.getKeyStorePassword());
ssl.setKeystoreType(SecurityManager.getKeyStoreType());

View File

@ -0,0 +1,169 @@
package net.i2p.i2pcontrol.router;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import net.i2p.I2PAppContext;
import net.i2p.crypto.KeyGenerator;
import net.i2p.data.Certificate;
import net.i2p.data.DataFormatException;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.data.RouterIdentity;
import net.i2p.data.RouterInfo;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
import net.i2p.data.SimpleDataStructure;
import net.i2p.i2pcontrol.util.IsJar;
import net.i2p.router.MultiRouter;
import net.i2p.router.MultiRouterBuilder;
import net.i2p.router.Router;
import net.i2p.router.RouterContext;
import net.i2p.router.startup.CreateRouterInfoJob;
import net.i2p.router.startup.RebuildRouterInfoJob;
import net.i2p.util.Log;
import net.i2p.util.SecureFileOutputStream;
/**
* Handle communications with the router instance.
* @author mathias
*
*/
public class RouterManager {
private final static Log _log = new Log(RouterManager.class);
private static I2PAppContext context = I2PAppContext.getCurrentContext();
private static boolean startedTestRouter = false;
private final static String I2P_DIR = "/home/hottuna/Apps/i2p/";
private final static String I2P_CONFIG_FILE = "/home/hottuna/.i2p/router.config";
public static I2PAppContext getAppContext() {
return context;
}
public static RouterContext getRouterContext() throws Exception {
// If not running as a plugin from within I2P.
if (!IsJar.isRunningJar() && !startedTestRouter){
context = buildMinimalRouter();
}
if(context.isRouterContext()) {
return (RouterContext) context;
}else {
throw new Exception("No RouterContext available!");
}
}
private static Router getRouter() {
try {
return getRouterContext().router();
} catch (Exception e) {
_log.error("Failed to get router. Why did we request it if no RouterContext is available?", e);
return null;
}
}
private static RouterContext buildMinimalRouter(){
Properties prp = new Properties();
prp.setProperty("i2p.dir.base", I2P_DIR);
prp.setProperty("i2p.dir.config", I2P_DIR);
prp.setProperty("router.pingFile", "testrouter.ping");
prp.setProperty("router.configLocation", I2P_CONFIG_FILE);
Router rtr = new Router(prp);
// Massive block stolen from CreateRouterInfoJob.
RouterInfo info = new RouterInfo();
FileOutputStream fos1 = null;
FileOutputStream fos2 = null;
try {
info.setAddresses(rtr.getContext().commSystem().createAddresses());
Properties stats = rtr.getContext().statPublisher().publishStatistics();
stats.setProperty(RouterInfo.PROP_NETWORK_ID, Router.NETWORK_ID+"");
rtr.getContext().router().addCapabilities(info);
info.setOptions(stats);
// not necessary, in constructor
//info.setPeers(new HashSet());
//info.setPublished(rtr.getCurrentPublishDate(rtr.getContext()));
RouterIdentity ident = new RouterIdentity();
Certificate cert = rtr.getContext().router().createCertificate();
ident.setCertificate(cert);
PublicKey pubkey = null;
PrivateKey privkey = null;
SigningPublicKey signingPubKey = null;
SigningPrivateKey signingPrivKey = null;
Object keypair[] = rtr.getContext().keyGenerator().generatePKIKeypair();
pubkey = (PublicKey)keypair[0];
privkey = (PrivateKey)keypair[1];
Object signingKeypair[] = rtr.getContext().keyGenerator().generateSigningKeypair();
signingPubKey = (SigningPublicKey)signingKeypair[0];
signingPrivKey = (SigningPrivateKey)signingKeypair[1];
ident.setPublicKey(pubkey);
ident.setSigningPublicKey(signingPubKey);
info.setIdentity(ident);
info.sign(signingPrivKey);
if (!info.isValid())
throw new DataFormatException("RouterInfo we just built is invalid: " + info);
String infoFilename = rtr.getContext().getProperty(Router.PROP_INFO_FILENAME, Router.PROP_INFO_FILENAME_DEFAULT);
File ifile = new File(rtr.getContext().getRouterDir(), infoFilename);
fos1 = new SecureFileOutputStream(ifile);
info.writeBytes(fos1);
String keyFilename = rtr.getContext().getProperty(Router.PROP_KEYS_FILENAME, Router.PROP_KEYS_FILENAME_DEFAULT);
File kfile = new File(rtr.getContext().getRouterDir(), keyFilename);
fos2 = new SecureFileOutputStream(kfile);
privkey.writeBytes(fos2);
signingPrivKey.writeBytes(fos2);
pubkey.writeBytes(fos2);
signingPubKey.writeBytes(fos2);
rtr.getContext().keyManager().setSigningPrivateKey(signingPrivKey);
rtr.getContext().keyManager().setSigningPublicKey(signingPubKey);
rtr.getContext().keyManager().setPrivateKey(privkey);
rtr.getContext().keyManager().setPublicKey(pubkey);
_log.info("Router info created and stored at " + ifile.getAbsolutePath() + " with private keys stored at " + kfile.getAbsolutePath());
} catch (DataFormatException dfe) {
_log.error("Error building the new router information", dfe);
} catch (IOException ioe) {
_log.error("Error writing out the new router information", ioe);
} finally {
if (fos1 != null) try { fos1.close(); } catch (IOException ioe) {}
if (fos2 != null) try { fos2.close(); } catch (IOException ioe) {}
}
rtr.setRouterInfo(info);
rtr.getContext().initAll();
return rtr.getContext();
}
private class SimpleRouterContext extends RouterContext{
public SimpleRouterContext(Router router) {
super(router);
}
public SimpleRouterContext(Router router, Properties prop) {
super(router, prop);
}
}
/*
private static boolean deletePingFile(){
return (new File("/tmp/router.ping")).delete();
}
*/
public static void main(String[] args){
try {
getRouterContext();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -13,7 +13,7 @@ public class AuthToken {
public AuthToken(String password){
String hash = SecurityManager.getPasswdHash(password);
this.id = SecurityManager.getHash(hash+ Calendar.getInstance().getTime());
this.id = SecurityManager.getHash(hash + Calendar.getInstance().getTimeInMillis());
Calendar expiry = Calendar.getInstance();
expiry.add(Calendar.DAY_OF_YEAR, VALIDITY_TIME);
this.expiry = expiry.getTime();

View File

@ -29,7 +29,6 @@ import javax.net.SocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import sun.misc.BASE64Encoder;
@ -140,7 +139,8 @@ public class SecurityManager {
SHA256Generator hashGen = new SHA256Generator(I2PAppContext.getGlobalContext());
byte[] bytes = string.getBytes();
bytes = hashGen.calculateHash(bytes).toByteArray();
return new String(Base64.encode(bytes));
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encodeBuffer(bytes).trim();
}

View File

@ -30,9 +30,11 @@ import javax.servlet.http.HttpServletResponse;
import net.i2p.I2PAppContext;
import net.i2p.util.Log;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.AuthHandler;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.AuthenticateHandler;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.EchoHandler;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.StatHandler;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.GetRateHandler;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.NetworkSettingHandler;
import net.i2p.i2pcontrol.servlets.jsonrpc2handlers.OLDNetworkInfoHandler;
import com.thetransactioncompany.jsonrpc2.*;
import com.thetransactioncompany.jsonrpc2.server.*;
@ -57,8 +59,9 @@ public class JSONRPC2Servlet extends HttpServlet{
disp = new Dispatcher();
disp.register(new EchoHandler());
disp.register(new StatHandler());
disp.register(new AuthHandler());
disp.register(new GetRateHandler());
disp.register(new AuthenticateHandler());
disp.register(new NetworkSettingHandler());
}
@Override

View File

@ -11,7 +11,22 @@ import javax.servlet.http.HttpServletResponse;
import net.i2p.I2PAppContext;
import net.i2p.util.Log;
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class LogServlet extends HttpServlet {
/**

View File

@ -10,7 +10,22 @@ import javax.servlet.http.HttpServletResponse;
import net.i2p.I2PAppContext;
import net.i2p.util.Log;
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class SettingsServlet extends HttpServlet {
/**

View File

@ -13,24 +13,41 @@ import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.server.MessageContext;
import com.thetransactioncompany.jsonrpc2.server.RequestHandler;
public class AuthHandler implements RequestHandler {
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
private String[] requiredArgs = {"password"};
public class AuthenticateHandler implements RequestHandler {
private String[] requiredArgs = {"Password"};
// Reports the method names of the handled requests
public String[] handledRequests() {
return new String[]{"authenticate"};
return new String[]{"Authenticate"};
}
// Processes the requests
public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) {
if (req.getMethod().equals("authenticate")) {
if (req.getMethod().equals("Authenticate")) {
JSONRPC2Error err = JSONRPC2Helper.validateParams(requiredArgs, req, JSONRPC2Helper.USE_NO_AUTH);
if (err != null)
return new JSONRPC2Response(err, req.getID());
HashMap inParams = (HashMap) req.getParams();
String pwd = (String) inParams.get("password");
String pwd = (String) inParams.get("Password");
// Try get an AuthToken
AuthToken token = SecurityManager.validatePasswd(pwd);
@ -39,7 +56,7 @@ public class AuthHandler implements RequestHandler {
}
Map outParams = new HashMap();
outParams.put("token", token.getId());
outParams.put("Token", token.getId());
return new JSONRPC2Response(outParams, req.getID());
} else {
// Method name not supported

View File

@ -12,23 +12,23 @@ import com.thetransactioncompany.jsonrpc2.server.RequestHandler;
public class EchoHandler implements RequestHandler {
private String[] requiredArgs = {"echo"};
private String[] requiredArgs = {"Echo"};
// Reports the method names of the handled requests
public String[] handledRequests() {
return new String[]{"echo"};
return new String[]{"Echo"};
}
// Processes the requests
public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) {
if (req.getMethod().equals("echo")) {
if (req.getMethod().equals("Echo")) {
JSONRPC2Error err = JSONRPC2Helper.validateParams(requiredArgs, req);
if (err != null)
return new JSONRPC2Response(err, req.getID());
HashMap inParams = (HashMap) req.getParams();
String echo = (String) inParams.get("echo");
String echo = (String) inParams.get("Echo");
Map outParams = new HashMap();
outParams.put("result", echo);
outParams.put("Result", echo);
return new JSONRPC2Response(outParams, req.getID());
}
else {

View File

@ -13,30 +13,47 @@ import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.server.MessageContext;
import com.thetransactioncompany.jsonrpc2.server.RequestHandler;
public class StatHandler implements RequestHandler {
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
private String[] requiredArgs = {"stat", "period"};
public class GetRateHandler implements RequestHandler {
private String[] requiredArgs = {"Stat", "Period"};
// Reports the method names of the handled requests
public String[] handledRequests() {
return new String[]{"getRate"};
return new String[]{"GetRate"};
}
// Processes the requests
public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) {
if (req.getMethod().equals("getRate")) {
if (req.getMethod().equals("GetRate")) {
JSONRPC2Error err = JSONRPC2Helper.validateParams(requiredArgs, req);
if (err != null)
return new JSONRPC2Response(err, req.getID());
HashMap inParams = (HashMap) req.getParams();
String input = (String) inParams.get("stat");
String input = (String) inParams.get("Stat");
if (input == null){
return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID());
}
long period;
try{
period = (Long) inParams.get("period");
period = (Long) inParams.get("Period");
} catch (NumberFormatException e){
return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID());
}
@ -53,7 +70,7 @@ public class StatHandler implements RequestHandler {
if (rate.getRate(period) == null)
return new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, req.getID());
Map outParams = new HashMap();
outParams.put("result", rate.getRate(period).getAverageValue());
outParams.put("Result", rate.getRate(period).getAverageValue());
return new JSONRPC2Response(outParams, req.getID());
}
return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID());

View File

@ -4,6 +4,22 @@ import org.json.simple.JSONObject;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Error;
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Represents a JSON-RPC 2.0 error that occured during the processing of a

View File

@ -10,6 +10,23 @@ import com.thetransactioncompany.jsonrpc2.JSONRPC2Error;
import com.thetransactioncompany.jsonrpc2.JSONRPC2ParamsType;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class JSONRPC2Helper {
public final static Boolean USE_NO_AUTH = false;
public final static Boolean USE_AUTH = true;
@ -71,7 +88,7 @@ public class JSONRPC2Helper {
* @return null if everything is fine, JSONRPC2Error for any corresponding error.
*/
private static JSONRPC2Error validateToken(HashMap params){
String tokenID = (String) params.get("token");
String tokenID = (String) params.get("Token");
if (tokenID == null){
return JSONRPC2ExtendedError.NO_TOKEN;
}

View File

@ -0,0 +1,271 @@
package net.i2p.i2pcontrol.servlets.jsonrpc2handlers;
import java.util.HashMap;
import java.util.Map;
import net.i2p.I2PAppContext;
import net.i2p.data.RouterInfo;
import net.i2p.i2pcontrol.I2PControlController;
import net.i2p.i2pcontrol.router.RouterManager;
import net.i2p.router.Router;
import net.i2p.router.RouterContext;
import net.i2p.router.transport.CommSystemFacadeImpl;
import net.i2p.router.transport.FIFOBandwidthRefiller;
import net.i2p.router.transport.TransportManager;
import net.i2p.router.transport.udp.UDPTransport;
import net.i2p.util.Log;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Error;
import com.thetransactioncompany.jsonrpc2.JSONRPC2ParamsType;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.server.MessageContext;
import com.thetransactioncompany.jsonrpc2.server.RequestHandler;
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class NetworkSettingHandler implements RequestHandler {
private static final int BW_BURST_PCT = 110;
private static RouterContext _context;
private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(NetworkSettingHandler.class);
static{
try {
_context = RouterManager.getRouterContext();
} catch (Exception e) {
_log.error("Unable to initialize RouterContext.", e);
}
}
// Reports the method names of the handled requests
public String[] handledRequests() {
return new String[]{"NetworkSetting"};
}
// Processes the requests
public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) {
if (req.getMethod().equals("NetworkSetting")) {
return process(req);
}else {
// Method name not supported
return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID());
}
}
private JSONRPC2Response process(JSONRPC2Request req){
JSONRPC2Error err = JSONRPC2Helper.validateParams(null, req);
if (err != null)
return new JSONRPC2Response(err, req.getID());
if (_context == null){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INTERNAL_ERROR.getCode(),
"RouterContext was not initialized. Query failed"),
req.getID());
}
HashMap inParams = (HashMap) req.getParams();
Map outParams = new HashMap();
boolean restartNeeded = false;
boolean settingsSaved = false;
String inParam;
if (inParams.containsKey("i2p.router.net.ntcp.port")){
String oldNTCPPort = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT);
if ((inParam = (String) inParams.get("i2p.router.net.ntcp.port")) != null){
if (oldNTCPPort == null || !oldNTCPPort.equals(inParam.trim())){
_context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT, inParam);
restartNeeded = true;
}
settingsSaved = true;
} else{
outParams.put("i2p.router.net.ntcp.port", oldNTCPPort);
}
}
if(inParams.containsKey("i2p.router.net.ntcp.hostname")){
String oldNTCPHostname = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME);
if ((inParam = (String) inParams.get("i2p.router.net.ntcp.hostname")) != null){
if (oldNTCPHostname == null || !oldNTCPHostname.equals(inParam.trim())){
_context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME, inParam);
restartNeeded = true;
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.ntcp.hostname", oldNTCPHostname);
}
}
if(inParams.containsKey("i2p.router.net.ntcp.autoip")){
String oldNTCPAutoIP = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_IP);
if ((inParam = (String) inParams.get("i2p.router.net.ntcp.autoip")) != null){
inParam = inParam.trim().toLowerCase();
if (oldNTCPAutoIP == null || !oldNTCPAutoIP.equals(inParam)){
if ("always".equals(inParam) || "true".equals(inParam) || "false".equals(inParam)){
_context.setProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_IP, inParam);
restartNeeded = true;
} else {
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.ntcp.autoip\" can only be always, true or false. " + inParam + " isn't valid."),
req.getID());
}
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.ntcp.autoip", oldNTCPAutoIP);
}
}
if (inParams.containsKey("i2p.router.net.ssu.port")){
String oldSSUPort = _context.getProperty(UDPTransport.PROP_EXTERNAL_PORT);
if ((inParam = (String) inParams.get("i2p.router.net.ssu.port")) != null){
if (oldSSUPort== null || !oldSSUPort.equals(inParam.trim())){
_context.router().setConfigSetting(UDPTransport.PROP_EXTERNAL_PORT, inParam);
_context.router().setConfigSetting(UDPTransport.PROP_INTERNAL_PORT, inParam);
restartNeeded = true;
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.ssu.port", oldSSUPort);
}
}
if (inParams.containsKey("i2p.router.net.ssu.hostname")){
String oldSSUHostname = _context.getProperty(UDPTransport.PROP_EXTERNAL_HOST);
if ((inParam = (String) inParams.get("i2p.router.net.ssu.hostname")) != null){
if (oldSSUHostname == null || !oldSSUHostname.equals(inParam.trim())){
_context.router().setConfigSetting(UDPTransport.PROP_EXTERNAL_HOST, inParam);
restartNeeded = true;
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.ssu.hostname", oldSSUHostname);
}
}
if (inParams.containsKey("i2p.router.net.ssu.autoip")){
String oldSSUAutoIP = _context.getProperty(UDPTransport.PROP_SOURCES);
if ((inParam = (String) inParams.get("i2p.router.net.ssu.autoip")) != null){
inParam = inParam.trim().toLowerCase();
if (oldSSUAutoIP == null || !oldSSUAutoIP.equals(inParam)){
if (inParam.equals("ssu") || inParam.equals("local,ssu") || inParam.equals("upnp,ssu") || inParam.equals("local,upnp,ssu")){
_context.router().setConfigSetting(UDPTransport.PROP_SOURCES, inParam);
restartNeeded = true;
} else {
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.ssu.autoip\" can only be ssu/local,upnp,ssu/local/ssu/upnp,ssu. " + inParam + " isn't valid."),
req.getID());
}
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.ssu.autoip", oldSSUAutoIP);
}
}
// Non-setable key.
if (inParams.containsKey("i2p.router.net.ssu.detectedip")){
if ((inParam = (String) inParams.get("i2p.router.net.ssu.autoip")) == null){
outParams.put("i2p.router.net.ssu.detectedip", _context.router().getRouterInfo().getTargetAddress("SSU"));
}
}
if (inParams.containsKey("i2p.router.net.upnp")){
String oldUPNP = _context.getProperty(TransportManager.PROP_ENABLE_UPNP);
if ((inParam = (String) inParams.get("i2p.router.net.upnp")) != null){
if (oldUPNP == null || !oldUPNP.equals(inParam.trim())){
_context.router().setConfigSetting(TransportManager.PROP_ENABLE_UPNP, inParam);
restartNeeded = true;
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.upnp", oldUPNP);
}
}
if (inParams.containsKey("i2p.router.net.bw.share")){
String oldShare = _context.router().getConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE);
if ((inParam = (String) inParams.get("i2p.router.net.bw.share")) != null){
if (oldShare == null || !oldShare.equals(inParam.trim())){
_context.router().setConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE, inParam);
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.bw.share", oldShare);
}
}
if (inParams.containsKey("i2p.router.net.bw.in")){
String oldBWIn = _context.getProperty(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH);
if ((inParam = (String) inParams.get("i2p.router.net.bw.in")) != null){
Integer rate;
try{
rate = Integer.parseInt(inParam);
if (rate < 0)
throw new NumberFormatException();
} catch (NumberFormatException e){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.bw.in\" A positive integer must supplied, " + inParam + " isn't valid"),
req.getID());
}
Integer burstRate = (rate * BW_BURST_PCT)/100;
if (oldBWIn == null || !oldBWIn.equals(rate.toString())){
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BURST_BANDWIDTH, burstRate.toString());
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH_PEAK, rate.toString());
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.bw.in", oldBWIn);
}
}
if (inParams.containsKey("i2p.router.net.bw.out")){
String oldBWOut = _context.getProperty(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH);
if ((inParam = (String) inParams.get("i2p.router.net.bw.out")) != null){
Integer rate;
try{
rate = Integer.parseInt(inParam);
if (rate < 0)
throw new NumberFormatException();
} catch (NumberFormatException e){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.bw.out\" A positive integer must supplied, " + inParam + " isn't valid"),
req.getID());
}
Integer burstRate = (rate * BW_BURST_PCT)/100;
if (oldBWOut == null || !oldBWOut.equals(rate.toString())){
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BURST_BANDWIDTH, burstRate.toString());
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH_PEAK, rate.toString());
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.bw.out", oldBWOut);
}
}
if (inParams.containsKey("i2p.router.net.laptopmode")){
String oldLaptopMode = _context.getProperty(UDPTransport.PROP_LAPTOP_MODE);
if ((inParam = (String) inParams.get("i2p.router.net.laptopmode")) != null){
if (oldLaptopMode == null || !oldLaptopMode.equals(inParam.trim())){
_context.setProperty(UDPTransport.PROP_LAPTOP_MODE, inParam);
}
settingsSaved = true;
} else {
outParams.put("i2p.router.net.laptopmode", oldLaptopMode);
}
}
outParams.put("SettingsSaved", settingsSaved);
outParams.put("RestartNeeded", restartNeeded);
return new JSONRPC2Response(outParams, req.getID());
}
}

View File

@ -0,0 +1,283 @@
package net.i2p.i2pcontrol.servlets.jsonrpc2handlers;
import java.util.HashMap;
import java.util.Map;
import net.i2p.I2PAppContext;
import net.i2p.data.RouterInfo;
import net.i2p.i2pcontrol.I2PControlController;
import net.i2p.i2pcontrol.router.RouterManager;
import net.i2p.router.Router;
import net.i2p.router.RouterContext;
import net.i2p.router.transport.CommSystemFacadeImpl;
import net.i2p.router.transport.FIFOBandwidthRefiller;
import net.i2p.router.transport.TransportManager;
import net.i2p.router.transport.udp.UDPTransport;
import net.i2p.util.Log;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Error;
import com.thetransactioncompany.jsonrpc2.JSONRPC2ParamsType;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.server.MessageContext;
import com.thetransactioncompany.jsonrpc2.server.RequestHandler;
/*
* Copyright 2011 hottuna (dev@robertfoss.se)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
public class OLDNetworkInfoHandler implements RequestHandler {
private static final int BW_BURST_PCT = 110;
private static RouterContext _context;
private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(OLDNetworkInfoHandler.class);
static{
try {
_context = RouterManager.getRouterContext();
} catch (Exception e) {
_log.error("Unable to initialize RouterContext.", e);
}
}
// Reports the method names of the handled requests
public String[] handledRequests() {
return new String[]{"getNetworkInfo", "setNetworkInfo"};
}
// Processes the requests
public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) {
if (req.getMethod().equals("getNetworkInfo")) {
return processGet(req, ctx);
} else if (req.getMethod().equals("setNetworkInfo")){
return processSet(req, ctx);
}else {
// Method name not supported
return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID());
}
}
// TODO: Everything
@SuppressWarnings("unchecked")
private JSONRPC2Response processGet(JSONRPC2Request req, MessageContext ctx){
JSONRPC2Error err = JSONRPC2Helper.validateParams(null, req);
if (err != null)
return new JSONRPC2Response(err, req.getID());
if (_context == null){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INTERNAL_ERROR.getCode(),
"RouterContext was not initialized. Query failed"),
req.getID());
}
HashMap inParams = (HashMap) req.getParams();
Map outParams = new HashMap();
/*
* i2p.router.net.ntcp.port
* i2p.router.net.ntcp.hostname
* i2p.router.net.ntcp.autoip // true|always|false //disables autodetect|disabled //disables ntcp
* i2p.router.net.ssu.port
* i2p.router.net.ssu.hostname
* i2p.router.net.ssu.detectedip
* i2p.router.net.ssu.autoip //[local,upnp,ssu] any of prev., in order |fixed // fixed = no detection
* i2p.router.net.upnp //
* i2p.router.net.bw.share
* i2p.router.net.bw.in
* i2p.router.net.bw.out
* i2p.router.net.laptopmode
*/
boolean returnAll = inParams.containsKey("all");
if (returnAll || inParams.containsKey("i2p.router.net.ntcp.port"))
outParams.put("i2p.router.net.ntcp.port", _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT));
if (returnAll || inParams.containsKey("i2p.router.net.ntcp.hostname"))
outParams.put("i2p.router.net.ntcp.hostname", _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME));
if (returnAll || inParams.containsKey("i2p.router.net.ntcp.autoip"))
outParams.put("i2p.router.net.ntcp.autoip", _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_IP));
if (returnAll || inParams.containsKey("i2p.router.net.ssu.port"))
outParams.put("i2p.router.net.ssu.port", _context.getProperty(UDPTransport.PROP_EXTERNAL_PORT));
if (returnAll || inParams.containsKey("i2p.router.net.ssu.hostname"))
outParams.put("i2p.router.net.ssu.hostname", _context.getProperty(UDPTransport.PROP_EXTERNAL_HOST));
if (returnAll || inParams.containsKey("i2p.router.net.ssu.autoip"))
outParams.put("i2p.router.net.ssu.autoip", _context.getProperty(UDPTransport.PROP_SOURCES));
if (returnAll || inParams.containsKey("i2p.router.net.ssu.detectedip")){
outParams.put("i2p.router.net.ssu.detectedip", _context.router().getRouterInfo().getTargetAddress("SSU"));
}
if (returnAll || inParams.containsKey("i2p.router.net.upnp"))
outParams.put("i2p.router.net.upnp", _context.getProperty(TransportManager.PROP_ENABLE_UPNP));
if (returnAll || inParams.containsKey("i2p.router.net.bw.share"))
outParams.put("i2p.router.net.bw.share", _context.router().getConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE));
if (returnAll || inParams.containsKey("i2p.router.net.bw.in"))
outParams.put("i2p.router.net.bw.in", _context.getProperty(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH));
if (returnAll || inParams.containsKey("i2p.router.net.bw.out"))
outParams.put("i2p.router.net.bw.out", _context.getProperty(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH));
if (returnAll || inParams.containsKey("i2p.router.net.laptopmode"))
outParams.put("i2p.router.net.laptopmode", _context.getProperty(UDPTransport.PROP_LAPTOP_MODE));
return new JSONRPC2Response(outParams, req.getID());
}
private JSONRPC2Response processSet(JSONRPC2Request req, MessageContext ctx){
JSONRPC2Error err = JSONRPC2Helper.validateParams(null, req);
if (err != null)
return new JSONRPC2Response(err, req.getID());
if (_context == null){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INTERNAL_ERROR.getCode(),
"RouterContext was not initialized. Query failed"),
req.getID());
}
HashMap inParams = (HashMap) req.getParams();
Map outParams = new HashMap();
/*
* require.restart - [true|false]
*/
boolean restartNeeded = false;
String inParam;
if ((inParam = (String) inParams.get("i2p.router.net.ntcp.port")) != null){
String oldNTCPPort = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT);
if (oldNTCPPort == null || !oldNTCPPort.equals(inParam.trim())){
_context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT, inParam);
outParams.put("i2p.router.net.ntcp.port", true);
restartNeeded = true;
}
}
if ((inParam = (String) inParams.get("i2p.router.net.ntcp.hostname")) != null){
String oldNTCPHostname = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME);
if (oldNTCPHostname == null || !oldNTCPHostname.equals(inParam.trim())){
_context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME, inParam);
outParams.put("i2p.router.net.ntcp.hostname", true);
restartNeeded = true;
}
}
if ((inParam = (String) inParams.get("i2p.router.net.ntcp.autoip")) != null){
String oldNTCPAutoIP = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_IP);
inParam = inParam.trim().toLowerCase();
if (oldNTCPAutoIP == null || !oldNTCPAutoIP.equals(inParam)){
if ("always".equals(inParam) || "true".equals(inParam) || "false".equals(inParam)){
_context.setProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_IP, inParam);
outParams.put("i2p.router.net.ntcp.autoip", true);
restartNeeded = true;
} else {
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.ntcp.autoip\" can only be always, true or false. " + inParam + " isn't valid."),
req.getID());
}
}
}
if ((inParam = (String) inParams.get("i2p.router.net.ssu.port")) != null){
String oldSSUPort = _context.getProperty(UDPTransport.PROP_EXTERNAL_PORT);
if (oldSSUPort== null || !oldSSUPort.equals(inParam.trim())){
_context.router().setConfigSetting(UDPTransport.PROP_EXTERNAL_PORT, inParam);
_context.router().setConfigSetting(UDPTransport.PROP_INTERNAL_PORT, inParam);
outParams.put("i2p.router.net.ssu.port", true);
restartNeeded = true;
}
}
if ((inParam = (String) inParams.get("i2p.router.net.ssu.hostname")) != null){
String oldSSUHostname = _context.getProperty(UDPTransport.PROP_EXTERNAL_HOST);
if (oldSSUHostname == null || !oldSSUHostname.equals(inParam.trim())){
_context.router().setConfigSetting(UDPTransport.PROP_EXTERNAL_HOST, inParam);
outParams.put("i2p.router.net.ssu.hostname", true);
restartNeeded = true;
}
}
if ((inParam = (String) inParams.get("i2p.router.net.ssu.autoip")) != null){
String oldSSUAutoIP = _context.getProperty(UDPTransport.PROP_SOURCES);
inParam = inParam.trim().toLowerCase();
if (oldSSUAutoIP == null || !oldSSUAutoIP.equals(inParam)){
if (inParam.equals("ssu") || inParam.equals("local,ssu") || inParam.equals("upnp,ssu") || inParam.equals("local,upnp,ssu")){
_context.router().setConfigSetting(UDPTransport.PROP_SOURCES, inParam);
outParams.put("i2p.router.net.ssu.autoip", true);
restartNeeded = true;
} else {
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.ssu.autoip\" can only be ssu/local,upnp,ssu/local/ssu/upnp,ssu. " + inParam + " isn't valid."),
req.getID());
}
}
}
if ((inParam = (String) inParams.get("i2p.router.net.upnp")) != null){
String oldUPNP = _context.getProperty(TransportManager.PROP_ENABLE_UPNP);
if (oldUPNP == null || !oldUPNP.equals(inParam.trim())){
_context.router().setConfigSetting(TransportManager.PROP_ENABLE_UPNP, inParam);
outParams.put("i2p.router.net.upnp", true);
restartNeeded = true;
}
}
if ((inParam = (String) inParams.get("i2p.router.net.bw.share")) != null){
String oldShare = _context.router().getConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE);
if (oldShare == null || !oldShare.equals(inParam.trim())){
_context.router().setConfigSetting(Router.PROP_BANDWIDTH_SHARE_PERCENTAGE, inParam);
outParams.put("i2p.router.net.bw.share", true);
}
}
if ((inParam = (String) inParams.get("i2p.router.net.bw.in")) != null){
String oldBWIn = _context.getProperty(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH);
Integer rate;
try{
rate = Integer.parseInt(inParam);
if (rate < 0)
throw new NumberFormatException();
} catch (NumberFormatException e){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.bw.in\" A positive integer must supplied, " + inParam + " isn't valid"),
req.getID());
}
Integer burstRate = (rate * BW_BURST_PCT)/100;
if (oldBWIn == null || !oldBWIn.equals(rate.toString())){
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BURST_BANDWIDTH, burstRate.toString());
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH_PEAK, rate.toString());
outParams.put("i2p.router.net.bw.in", true);
}
}
if ((inParam = (String) inParams.get("i2p.router.net.bw.out")) != null){
String oldBWOut = _context.getProperty(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH);
Integer rate;
try{
rate = Integer.parseInt(inParam);
if (rate < 0)
throw new NumberFormatException();
} catch (NumberFormatException e){
return new JSONRPC2Response(
new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
"\"i2p.router.net.bw.out\" A positive integer must supplied, " + inParam + " isn't valid"),
req.getID());
}
Integer burstRate = (rate * BW_BURST_PCT)/100;
if (oldBWOut == null || !oldBWOut.equals(rate.toString())){
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BURST_BANDWIDTH, burstRate.toString());
_context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH_PEAK, rate.toString());
outParams.put("i2p.router.net.bw.out", true);
}
}
if ((inParam = (String) inParams.get("i2p.router.net.laptopmode")) != null){
String oldLaptopMode = _context.getProperty(UDPTransport.PROP_LAPTOP_MODE);
if (oldLaptopMode == null || !oldLaptopMode.equals(inParam.trim())){
_context.setProperty(UDPTransport.PROP_LAPTOP_MODE, inParam);
outParams.put("i2p.router.net.laptopmode", true);
}
}
outParams.put("restart.needed", restartNeeded);
return new JSONRPC2Response(outParams, req.getID());
}
}

View File

@ -0,0 +1,14 @@
package net.i2p.i2pcontrol.util;
public abstract class IsJar {
public static boolean isRunningJar(){
IsJarTester isJar = new IsJarTester();
String className = isJar.getClass().getName().replace('.', '/');
String classJar = isJar.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:"))
return true;
else
return false;
}
}

View File

@ -0,0 +1,5 @@
package net.i2p.i2pcontrol.util;
public class IsJarTester {
}