From c721c9ab48d565eb5cb4dc9d7456ec7a444c7889 Mon Sep 17 00:00:00 2001 From: str4d Date: Tue, 16 Oct 2012 04:14:12 +0000 Subject: [PATCH] Finished fixing inconsistent whitespace --- .../i2pcontrol/servlets/JSONRPC2Servlet.java | 118 ++--- .../configuration/ConfigurationManager.java | 394 +++++++------- .../jsonrpc2handlers/AuthenticateHandler.java | 126 ++--- .../jsonrpc2handlers/EchoHandler.java | 48 +- .../jsonrpc2handlers/GetRateHandler.java | 88 ++-- .../jsonrpc2handlers/I2PControlHandler.java | 286 +++++----- .../JSONRPC2ExtendedError.java | 182 +++---- .../jsonrpc2handlers/JSONRPC2Helper.java | 151 +++--- .../NetworkSettingHandler.java | 489 +++++++++--------- .../jsonrpc2handlers/RouterInfoHandler.java | 330 ++++++------ .../RouterManagerHandler.java | 218 ++++---- 11 files changed, 1213 insertions(+), 1217 deletions(-) diff --git a/src/java/net/i2p/i2pcontrol/servlets/JSONRPC2Servlet.java b/src/java/net/i2p/i2pcontrol/servlets/JSONRPC2Servlet.java index 90577ea..37ec5f3 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/JSONRPC2Servlet.java +++ b/src/java/net/i2p/i2pcontrol/servlets/JSONRPC2Servlet.java @@ -50,72 +50,72 @@ import com.thetransactioncompany.jsonrpc2.server.*; */ public class JSONRPC2Servlet extends HttpServlet{ - private static final long serialVersionUID = -45075606818515212L; - private static final int BUFFER_LENGTH = 2048; - private static Dispatcher disp; - private static char[] readBuffer; - private static Log _log; + private static final long serialVersionUID = -45075606818515212L; + private static final int BUFFER_LENGTH = 2048; + private static Dispatcher disp; + private static char[] readBuffer; + private static Log _log; - - @Override - public void init(){ - _log = I2PAppContext.getGlobalContext().logManager().getLog(JSONRPC2Servlet.class); - readBuffer = new char[BUFFER_LENGTH]; - - disp = new Dispatcher(); - disp.register(new EchoHandler()); - disp.register(new GetRateHandler()); - disp.register(new AuthenticateHandler()); - disp.register(new NetworkSettingHandler()); - disp.register(new RouterInfoHandler()); - disp.register(new RouterManagerHandler()); - disp.register(new I2PControlHandler()); - } - - @Override + + @Override + public void init(){ + _log = I2PAppContext.getGlobalContext().logManager().getLog(JSONRPC2Servlet.class); + readBuffer = new char[BUFFER_LENGTH]; + + disp = new Dispatcher(); + disp.register(new EchoHandler()); + disp.register(new GetRateHandler()); + disp.register(new AuthenticateHandler()); + disp.register(new NetworkSettingHandler()); + disp.register(new RouterInfoHandler()); + disp.register(new RouterManagerHandler()); + disp.register(new I2PControlHandler()); + } + + @Override protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException{ - httpServletResponse.setContentType("text/html"); + httpServletResponse.setContentType("text/html"); PrintWriter out = httpServletResponse.getWriter(); out.println("Nothing to see here"); out.close(); } - - @Override - protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException{ - String req = getRequest(httpServletRequest.getInputStream()); - httpServletResponse.setContentType("application/json"); - PrintWriter out = httpServletResponse.getWriter(); - JSONRPC2Message msg = null; - JSONRPC2Response jsonResp = null; - try { - msg = JSONRPC2Message.parse(req); - if (msg instanceof JSONRPC2Request) { - jsonResp = disp.dispatch((JSONRPC2Request)msg, null); - jsonResp.toJSON().put("API", I2PControlVersion.API_VERSION); - _log.debug("Request: " + msg); - _log.debug("Response: " + jsonResp); - } - else if (msg instanceof JSONRPC2Notification) { - disp.dispatch((JSONRPC2Notification)msg, null); - _log.debug("Notification: " + msg); - } - - out.println(jsonResp); - out.close(); - } catch (JSONRPC2ParseException e) { - _log.error("Unable to parse JSONRPC2Message: " + e.getMessage()); - } - } - + @Override + protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException{ + String req = getRequest(httpServletRequest.getInputStream()); + httpServletResponse.setContentType("application/json"); + PrintWriter out = httpServletResponse.getWriter(); + JSONRPC2Message msg = null; + JSONRPC2Response jsonResp = null; + try { + msg = JSONRPC2Message.parse(req); + + if (msg instanceof JSONRPC2Request) { + jsonResp = disp.dispatch((JSONRPC2Request)msg, null); + jsonResp.toJSON().put("API", I2PControlVersion.API_VERSION); + _log.debug("Request: " + msg); + _log.debug("Response: " + jsonResp); + } + else if (msg instanceof JSONRPC2Notification) { + disp.dispatch((JSONRPC2Notification)msg, null); + _log.debug("Notification: " + msg); + } + + out.println(jsonResp); + out.close(); + } catch (JSONRPC2ParseException e) { + _log.error("Unable to parse JSONRPC2Message: " + e.getMessage()); + } + } + private String getRequest(ServletInputStream sis) throws IOException{ - Writer writer = new StringWriter(); - - BufferedReader reader = new BufferedReader(new InputStreamReader(sis,"UTF-8")); - int n; - while ((n = reader.read(readBuffer)) != -1) { - writer.write(readBuffer, 0, n); - } - return writer.toString(); + Writer writer = new StringWriter(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(sis,"UTF-8")); + int n; + while ((n = reader.read(readBuffer)) != -1) { + writer.write(readBuffer, 0, n); + } + return writer.toString(); } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/configuration/ConfigurationManager.java b/src/java/net/i2p/i2pcontrol/servlets/configuration/ConfigurationManager.java index 6257053..521c731 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/configuration/ConfigurationManager.java +++ b/src/java/net/i2p/i2pcontrol/servlets/configuration/ConfigurationManager.java @@ -23,203 +23,203 @@ import net.i2p.util.Log; * */ public class ConfigurationManager { - private static String configLocation = "I2PControl.conf"; - private static boolean configLocationModified = false; - private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(ConfigurationManager.class); - - private static ConfigurationManager instance; - //Configurations with a String as value - private static Map stringConfigurations = new HashMap(); - //Configurations with a Boolean as value - private static Map booleanConfigurations = new HashMap(); - //Configurations with an Integer as value - private static Map integerConfigurations = new HashMap(); + private static String configLocation = "I2PControl.conf"; + private static boolean configLocationModified = false; + private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(ConfigurationManager.class); - - /** - * Should only be set before getInstance is first called. - * @param dir - */ - public static void setConfDir(String dir){ - if (!configLocationModified){ - if (dir.endsWith("/")){ - configLocation = dir + configLocation; - } else { - configLocation = dir + "/" + configLocation; - } - } - } - - private ConfigurationManager() { - readConfFile(); - } - - public synchronized static ConfigurationManager getInstance() { - if(instance == null) { - instance = new ConfigurationManager(); - } - return instance; - } - - /** - * Collects settingNameuments of the form --word, --word=otherword and -blah - * to determine user parameters. - * @param settingNames Command line settingNameuments to the application - */ - public void loadsettingNameuments(String[] settingNames) { - for(int i=0; i tree = new TreeMap(); - for (Entry e : stringConfigurations.entrySet()){ - tree.put(e.getKey(), e.getValue()); - } - for (Entry e : integerConfigurations.entrySet()){ - tree.put(e.getKey(), e.getValue().toString()); - } - for (Entry e : booleanConfigurations.entrySet()){ - tree.put(e.getKey(), e.getValue().toString()); - } - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(configLocation)); - for (Entry e : tree.entrySet()){ - bw.write(e.getKey() + "=" + e.getValue() + "\r\n"); - } - bw.close(); - } catch (IOException e1) { - _log.error("Couldn't open file, " + configLocation + " for writing config."); - } - } - - /** - * Try to parse the given line as 'key=value', - * where value will (in order) be parsed as integer/boolean/string. - * @param str - */ - public static void parseConfigStr(String str){ - int eqIndex = str.indexOf('='); - if (eqIndex != -1){ - String key = str.substring(0, eqIndex).trim().toLowerCase(); - String value = str.substring(eqIndex+1, str.length()).trim(); - //Try parse as integer. - try { - int i = Integer.parseInt(value); - integerConfigurations.put(key, i); - return; - } catch (NumberFormatException e){} - //Check if value is a bool - if (value.toLowerCase().equals("true")){ - booleanConfigurations.put(key, Boolean.TRUE); - return; - } else if (value.toLowerCase().equals("false")){ - booleanConfigurations.put(key, Boolean.FALSE); - return; - } - stringConfigurations.put(key, value); - } - } + private static ConfigurationManager instance; + //Configurations with a String as value + private static Map stringConfigurations = new HashMap(); + //Configurations with a Boolean as value + private static Map booleanConfigurations = new HashMap(); + //Configurations with an Integer as value + private static Map integerConfigurations = new HashMap(); - - /** - * Check if a specific boolean configuration exists. - * @param settingName The key for the configuration. - * @param defaultValue If the configuration is not found, we use a default value. - * @return The value of a configuration: true if found, defaultValue if not found. - */ - public boolean getConf(String settingName, boolean defaultValue) { - Boolean value = booleanConfigurations.get(settingName); - if(value != null) { - return value; - } else { - booleanConfigurations.put(settingName, defaultValue); - return defaultValue; - } - } - - - /** - * Check if a specific boolean configuration exists. - * @param settingName The key for the configuration. - * @param defaultValue If the configuration is not found, we use a default value. - * @return The value of a configuration: true if found, defaultValue if not found. - */ - public int getConf(String settingName, int defaultValue) { - Integer value = integerConfigurations.get(settingName); - if(value != null) { - return value; - } else { - integerConfigurations.put(settingName, defaultValue); - return defaultValue; - } - } - - /** - * Get a specific String configuration. - * @param settingName The key for the configuration. - * @param defaultValue If the configuration is not found, we use a default value. - * @return The value of the configuration, or the defaultValue. - */ - public String getConf(String settingName, String defaultValue) { - String value = stringConfigurations.get(settingName); - if(value != null) { - return value; - } else { - stringConfigurations.put(settingName, defaultValue); - return defaultValue; - } - } - - /** - * Set a specific int setting - * @param settingName - * @param nbr - */ - public void setConf(String settingName, int nbr){ - integerConfigurations.put(settingName, nbr); - } - - /** - * Set a specific string setting - * @param settingName - * @param string - */ - public void setConf(String settingName, String str){ - stringConfigurations.put(settingName, str); - } - - /** - * Set a specific boolean setting - * @param settingName - * @param boolean - */ - public void setConf(String settingName, boolean bool){ - booleanConfigurations.put(settingName, bool); - } + + /** + * Should only be set before getInstance is first called. + * @param dir + */ + public static void setConfDir(String dir){ + if (!configLocationModified){ + if (dir.endsWith("/")){ + configLocation = dir + configLocation; + } else { + configLocation = dir + "/" + configLocation; + } + } + } + + private ConfigurationManager() { + readConfFile(); + } + + public synchronized static ConfigurationManager getInstance() { + if(instance == null) { + instance = new ConfigurationManager(); + } + return instance; + } + + /** + * Collects settingNameuments of the form --word, --word=otherword and -blah + * to determine user parameters. + * @param settingNames Command line settingNameuments to the application + */ + public void loadsettingNameuments(String[] settingNames) { + for(int i=0; i tree = new TreeMap(); + for (Entry e : stringConfigurations.entrySet()){ + tree.put(e.getKey(), e.getValue()); + } + for (Entry e : integerConfigurations.entrySet()){ + tree.put(e.getKey(), e.getValue().toString()); + } + for (Entry e : booleanConfigurations.entrySet()){ + tree.put(e.getKey(), e.getValue().toString()); + } + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(configLocation)); + for (Entry e : tree.entrySet()){ + bw.write(e.getKey() + "=" + e.getValue() + "\r\n"); + } + bw.close(); + } catch (IOException e1) { + _log.error("Couldn't open file, " + configLocation + " for writing config."); + } + } + + /** + * Try to parse the given line as 'key=value', + * where value will (in order) be parsed as integer/boolean/string. + * @param str + */ + public static void parseConfigStr(String str){ + int eqIndex = str.indexOf('='); + if (eqIndex != -1){ + String key = str.substring(0, eqIndex).trim().toLowerCase(); + String value = str.substring(eqIndex+1, str.length()).trim(); + //Try parse as integer. + try { + int i = Integer.parseInt(value); + integerConfigurations.put(key, i); + return; + } catch (NumberFormatException e){} + //Check if value is a bool + if (value.toLowerCase().equals("true")){ + booleanConfigurations.put(key, Boolean.TRUE); + return; + } else if (value.toLowerCase().equals("false")){ + booleanConfigurations.put(key, Boolean.FALSE); + return; + } + stringConfigurations.put(key, value); + } + } + + + /** + * Check if a specific boolean configuration exists. + * @param settingName The key for the configuration. + * @param defaultValue If the configuration is not found, we use a default value. + * @return The value of a configuration: true if found, defaultValue if not found. + */ + public boolean getConf(String settingName, boolean defaultValue) { + Boolean value = booleanConfigurations.get(settingName); + if(value != null) { + return value; + } else { + booleanConfigurations.put(settingName, defaultValue); + return defaultValue; + } + } + + + /** + * Check if a specific boolean configuration exists. + * @param settingName The key for the configuration. + * @param defaultValue If the configuration is not found, we use a default value. + * @return The value of a configuration: true if found, defaultValue if not found. + */ + public int getConf(String settingName, int defaultValue) { + Integer value = integerConfigurations.get(settingName); + if(value != null) { + return value; + } else { + integerConfigurations.put(settingName, defaultValue); + return defaultValue; + } + } + + /** + * Get a specific String configuration. + * @param settingName The key for the configuration. + * @param defaultValue If the configuration is not found, we use a default value. + * @return The value of the configuration, or the defaultValue. + */ + public String getConf(String settingName, String defaultValue) { + String value = stringConfigurations.get(settingName); + if(value != null) { + return value; + } else { + stringConfigurations.put(settingName, defaultValue); + return defaultValue; + } + } + + /** + * Set a specific int setting + * @param settingName + * @param nbr + */ + public void setConf(String settingName, int nbr){ + integerConfigurations.put(settingName, nbr); + } + + /** + * Set a specific string setting + * @param settingName + * @param string + */ + public void setConf(String settingName, String str){ + stringConfigurations.put(settingName, str); + } + + /** + * Set a specific boolean setting + * @param settingName + * @param boolean + */ + public void setConf(String settingName, boolean bool){ + booleanConfigurations.put(settingName, bool); + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/AuthenticateHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/AuthenticateHandler.java index a1ff5e6..bc340cd 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/AuthenticateHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/AuthenticateHandler.java @@ -33,67 +33,67 @@ import com.thetransactioncompany.jsonrpc2.server.RequestHandler; public class AuthenticateHandler implements RequestHandler { - private String[] requiredArgs = {"Password","API"}; - // Reports the method names of the handled requests - public String[] handledRequests() { - return new String[]{"Authenticate"}; - } - - // Processes the requests - public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { - 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"); - - // Try get an AuthToken - - AuthToken token = SecurityManager.getInstance().validatePasswd(pwd); - if (token == null){ - return new JSONRPC2Response(JSONRPC2ExtendedError.INVALID_PASSWORD, req.getID()); - } - - Object api = inParams.get("API"); - err = validateAPIVersion(api); - if (err != null) - return new JSONRPC2Response(err, req.getID()); - - - Map outParams = new HashMap(); - outParams.put("Token", token.getId()); - outParams.put("API", I2PControlVersion.API_VERSION); - return new JSONRPC2Response(outParams, req.getID()); - } else { - // Method name not supported - return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); - } - } - - /** - * Validate the provided I2PControl API version against the ones supported by I2PControl. - */ - private static JSONRPC2Error validateAPIVersion(Object api){ - - Integer apiVersion; - try { - apiVersion = ((Long) api).intValue(); - } catch (ClassCastException e){ - e.printStackTrace(); - return JSONRPC2ExtendedError.UNSPECIFIED_API_VERSION; - } - - if (!I2PControlVersion.SUPPORTED_API_VERSIONS.contains(apiVersion)){ - String supportedAPIVersions = ""; - for (Integer i : I2PControlVersion.SUPPORTED_API_VERSIONS){ - supportedAPIVersions += ", "+ i; - } - return new JSONRPC2Error(JSONRPC2ExtendedError.UNSUPPORTED_API_VERSION.getCode(), - "The provided API version \'" + apiVersion + "\' is not supported. The supported versions are" + supportedAPIVersions+"."); - } - return null; - } + private String[] requiredArgs = {"Password","API"}; + // Reports the method names of the handled requests + public String[] handledRequests() { + return new String[]{"Authenticate"}; + } + + // Processes the requests + public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { + 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"); + + // Try get an AuthToken + + AuthToken token = SecurityManager.getInstance().validatePasswd(pwd); + if (token == null){ + return new JSONRPC2Response(JSONRPC2ExtendedError.INVALID_PASSWORD, req.getID()); + } + + Object api = inParams.get("API"); + err = validateAPIVersion(api); + if (err != null) + return new JSONRPC2Response(err, req.getID()); + + + Map outParams = new HashMap(); + outParams.put("Token", token.getId()); + outParams.put("API", I2PControlVersion.API_VERSION); + return new JSONRPC2Response(outParams, req.getID()); + } else { + // Method name not supported + return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); + } + } + + /** + * Validate the provided I2PControl API version against the ones supported by I2PControl. + */ + private static JSONRPC2Error validateAPIVersion(Object api){ + + Integer apiVersion; + try { + apiVersion = ((Long) api).intValue(); + } catch (ClassCastException e){ + e.printStackTrace(); + return JSONRPC2ExtendedError.UNSPECIFIED_API_VERSION; + } + + if (!I2PControlVersion.SUPPORTED_API_VERSIONS.contains(apiVersion)){ + String supportedAPIVersions = ""; + for (Integer i : I2PControlVersion.SUPPORTED_API_VERSIONS){ + supportedAPIVersions += ", "+ i; + } + return new JSONRPC2Error(JSONRPC2ExtendedError.UNSUPPORTED_API_VERSION.getCode(), + "The provided API version \'" + apiVersion + "\' is not supported. The supported versions are" + supportedAPIVersions+"."); + } + return null; + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/EchoHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/EchoHandler.java index 8552145..84c1fc4 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/EchoHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/EchoHandler.java @@ -12,28 +12,28 @@ import com.thetransactioncompany.jsonrpc2.server.RequestHandler; public class EchoHandler implements RequestHandler { - private String[] requiredArgs = {"Echo"}; - // Reports the method names of the handled requests - public String[] handledRequests() { - return new String[]{"Echo"}; - } - - // Processes the requests - public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { - 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"); - Map outParams = new HashMap(); - outParams.put("Result", echo); - return new JSONRPC2Response(outParams, req.getID()); - } - else { - // Method name not supported - return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); - } - } + private String[] requiredArgs = {"Echo"}; + // Reports the method names of the handled requests + public String[] handledRequests() { + return new String[]{"Echo"}; + } + + // Processes the requests + public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { + 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"); + Map outParams = new HashMap(); + outParams.put("Result", echo); + return new JSONRPC2Response(outParams, req.getID()); + } + else { + // Method name not supported + return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); + } + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/GetRateHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/GetRateHandler.java index e0ea7ff..559ad0c 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/GetRateHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/GetRateHandler.java @@ -33,49 +33,49 @@ import com.thetransactioncompany.jsonrpc2.server.RequestHandler; 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"}; - } - - // Processes the requests - public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { - 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"); - if (input == null){ - return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID()); - } - long period; - try{ - period = (Long) inParams.get("Period"); - } catch (NumberFormatException e){ - return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID()); - } + private String[] requiredArgs = {"Stat", "Period"}; + // Reports the method names of the handled requests + public String[] handledRequests() { + return new String[]{"GetRate"}; + } - RateStat rateStat = I2PAppContext.getGlobalContext().statManager().getRate(input); - - // If RateStat or the requested period doesn't already exist, create them. - if (rateStat == null || rateStat.getRate(period) == null){ - long[] tempArr = new long[1]; - tempArr[0] = period; - I2PAppContext.getGlobalContext().statManager().createRequiredRateStat(input, "I2PControl", "I2PControl", tempArr); - rateStat = I2PAppContext.getGlobalContext().statManager().getRate(input); - } - if (rateStat.getRate(period) == null) - return new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, req.getID()); - Map outParams = new HashMap(); - Rate rate = rateStat.getRate(period); - rate.coalesce(); - outParams.put("Result", rate.getAverageValue()); - return new JSONRPC2Response(outParams, req.getID()); - } - return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); - } + // Processes the requests + public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { + 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"); + if (input == null){ + return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID()); + } + long period; + try{ + period = (Long) inParams.get("Period"); + } catch (NumberFormatException e){ + return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID()); + } + + RateStat rateStat = I2PAppContext.getGlobalContext().statManager().getRate(input); + + // If RateStat or the requested period doesn't already exist, create them. + if (rateStat == null || rateStat.getRate(period) == null){ + long[] tempArr = new long[1]; + tempArr[0] = period; + I2PAppContext.getGlobalContext().statManager().createRequiredRateStat(input, "I2PControl", "I2PControl", tempArr); + rateStat = I2PAppContext.getGlobalContext().statManager().getRate(input); + } + if (rateStat.getRate(period) == null) + return new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, req.getID()); + Map outParams = new HashMap(); + Rate rate = rateStat.getRate(period); + rate.coalesce(); + outParams.put("Result", rate.getAverageValue()); + return new JSONRPC2Response(outParams, req.getID()); + } + return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/I2PControlHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/I2PControlHandler.java index 88dc095..9a61315 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/I2PControlHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/I2PControlHandler.java @@ -44,154 +44,152 @@ public class I2PControlHandler implements RequestHandler { private static RouterContext _context; private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(I2PControlHandler.class); private static final ConfigurationManager _conf = ConfigurationManager.getInstance(); - + static{ - try { - _context = RouterManager.getRouterContext(); - } catch (Exception e) { - _log.error("Unable to initialize RouterContext.", e); - } + 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[]{"I2PControl"}; - } - - // Processes the requests - public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { - if (req.getMethod().equals("I2PControl")) { - 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("i2pcontrol.port")){ - Integer oldPort = _conf.getConf("i2pcontrol.listen.port", 7650); - if ((inParam = (String) inParams.get("i2pcontrol.port")) != null){ - if (oldPort == null || !inParam.equals(oldPort.toString())){ - Integer newPort; - try { - newPort = Integer.valueOf(inParam); - if (newPort < 1 || newPort > 65535){ - throw new NumberFormatException(); - } - } catch (NumberFormatException e){ - return new JSONRPC2Response( - new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), - "\"i2pcontrol.port\" must be a string representing a number in the range 1-65535. " + inParam + " isn't valid."), - req.getID()); - } - try { - SslSocketConnector ssl = I2PControlController.buildSslListener(_conf.getConf("i2pcontrol.listen.address", "127.0.0.1"), newPort); - I2PControlController.clearListeners(); - I2PControlController.replaceListener(ssl); - - _conf.setConf("i2pcontrol.listen.port", newPort); + // Reports the method names of the handled requests + public String[] handledRequests() { + return new String[]{"I2PControl"}; + } - - ConfigurationManager.writeConfFile(); - outParams.put("i2pcontrol.port", null); - settingsSaved = true; - } catch (Exception e) { - try { - _conf.setConf("i2pcontrol.listen.port", oldPort); - SslSocketConnector ssl = I2PControlController.buildSslListener(_conf.getConf("i2pcontrol.listen.address", "127.0.0.1"), newPort); - I2PControlController.clearListeners(); - I2PControlController.replaceListener(ssl); - } catch (Exception e2){ - _log.log(Log.CRIT, "Unable to resume server on previous listening port." ); - } - _log.error("Client tried to set listen port to, " + newPort + " which isn't valid.", e); - return new JSONRPC2Response( - new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), - "\"i2pcontrol.port\" has been set to a port that is already in use, reverting. " + - inParam + " is an already used port."), - req.getID()); - } - } - } - } - - if(inParams.containsKey("i2pcontrol.password")){ - if ((inParam = (String) inParams.get("i2pcontrol.password")) != null){ - if (SecurityManager.getInstance().setPasswd(inParam)){ - outParams.put("i2pcontrol.password", null); - settingsSaved = true; - } - ConfigurationManager.writeConfFile(); - } - } - - if(inParams.containsKey("i2pcontrol.address")){ - String oldAddress = _conf.getConf("i2pcontrol.listen.address", "127.0.0.1"); - if ((inParam = (String) inParams.get("i2pcontrol.address")) != null){ - if ((oldAddress == null || !inParam.equals(oldAddress.toString()) && - (inParam.equals("0.0.0.0") || inParam.equals("127.0.0.1")))){ - InetAddress[] newAddress; + // Processes the requests + public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { + if (req.getMethod().equals("I2PControl")) { + return process(req); + }else { + // Method name not supported + return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, req.getID()); + } + } - try { - newAddress = InetAddress.getAllByName(inParam); - } catch (UnknownHostException e){ - return new JSONRPC2Response( - new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), - "\"i2pcontrol.address\" must be a string representing a hostname or ipaddress. " + inParam + " isn't valid."), - req.getID()); - } - try { - SslSocketConnector ssl = I2PControlController.buildSslListener(inParam, _conf.getConf("i2pcontrol.listen.port", 7650)); - I2PControlController.clearListeners(); - I2PControlController.replaceListener(ssl); - _conf.setConf("i2pcontrol.listen.address", inParam); - ConfigurationManager.writeConfFile(); - outParams.put("i2pcontrol.address", null); - settingsSaved = true; - } catch (Exception e) { - _conf.setConf("i2pcontrol.listen.address", oldAddress); - try { - SslSocketConnector ssl = I2PControlController.buildSslListener(inParam, _conf.getConf("i2pcontrol.listen.port", 7650)); - I2PControlController.clearListeners(); - I2PControlController.replaceListener(ssl); - } catch (Exception e2){ - _log.log(Log.CRIT, "Unable to resume server on previous listening ip." ); - } - _log.error("Client tried to set listen address to, " + newAddress.toString() + " which isn't valid.", e); - return new JSONRPC2Response( - new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), - "\"i2pcontrol.address\" has been set to an invalid address, reverting. "), req.getID()); - } - } - } else { - outParams.put("i2pcontrol.address", oldAddress); - } - } - - - outParams.put("SettingsSaved", settingsSaved); - outParams.put("RestartNeeded", restartNeeded); - return new JSONRPC2Response(outParams, 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("i2pcontrol.port")){ + Integer oldPort = _conf.getConf("i2pcontrol.listen.port", 7650); + if ((inParam = (String) inParams.get("i2pcontrol.port")) != null){ + if (oldPort == null || !inParam.equals(oldPort.toString())){ + Integer newPort; + try { + newPort = Integer.valueOf(inParam); + if (newPort < 1 || newPort > 65535){ + throw new NumberFormatException(); + } + } catch (NumberFormatException e){ + return new JSONRPC2Response( + new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), + "\"i2pcontrol.port\" must be a string representing a number in the range 1-65535. " + inParam + " isn't valid."), + req.getID()); + } + try { + SslSocketConnector ssl = I2PControlController.buildSslListener(_conf.getConf("i2pcontrol.listen.address", "127.0.0.1"), newPort); + I2PControlController.clearListeners(); + I2PControlController.replaceListener(ssl); + + _conf.setConf("i2pcontrol.listen.port", newPort); + + + ConfigurationManager.writeConfFile(); + outParams.put("i2pcontrol.port", null); + settingsSaved = true; + } catch (Exception e) { + try { + _conf.setConf("i2pcontrol.listen.port", oldPort); + SslSocketConnector ssl = I2PControlController.buildSslListener(_conf.getConf("i2pcontrol.listen.address", "127.0.0.1"), newPort); + I2PControlController.clearListeners(); + I2PControlController.replaceListener(ssl); + } catch (Exception e2){ + _log.log(Log.CRIT, "Unable to resume server on previous listening port." ); + } + _log.error("Client tried to set listen port to, " + newPort + " which isn't valid.", e); + return new JSONRPC2Response( + new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), + "\"i2pcontrol.port\" has been set to a port that is already in use, reverting. " + + inParam + " is an already used port."), + req.getID()); + } + } + } + } + + if(inParams.containsKey("i2pcontrol.password")){ + if ((inParam = (String) inParams.get("i2pcontrol.password")) != null){ + if (SecurityManager.getInstance().setPasswd(inParam)){ + outParams.put("i2pcontrol.password", null); + settingsSaved = true; + } + ConfigurationManager.writeConfFile(); + } + } + + if(inParams.containsKey("i2pcontrol.address")){ + String oldAddress = _conf.getConf("i2pcontrol.listen.address", "127.0.0.1"); + if ((inParam = (String) inParams.get("i2pcontrol.address")) != null){ + if ((oldAddress == null || !inParam.equals(oldAddress.toString()) && + (inParam.equals("0.0.0.0") || inParam.equals("127.0.0.1")))){ + InetAddress[] newAddress; + + try { + newAddress = InetAddress.getAllByName(inParam); + } catch (UnknownHostException e){ + return new JSONRPC2Response( + new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), + "\"i2pcontrol.address\" must be a string representing a hostname or ipaddress. " + inParam + " isn't valid."), + req.getID()); + } + try { + SslSocketConnector ssl = I2PControlController.buildSslListener(inParam, _conf.getConf("i2pcontrol.listen.port", 7650)); + I2PControlController.clearListeners(); + I2PControlController.replaceListener(ssl); + _conf.setConf("i2pcontrol.listen.address", inParam); + + ConfigurationManager.writeConfFile(); + outParams.put("i2pcontrol.address", null); + settingsSaved = true; + } catch (Exception e) { + _conf.setConf("i2pcontrol.listen.address", oldAddress); + try { + SslSocketConnector ssl = I2PControlController.buildSslListener(inParam, _conf.getConf("i2pcontrol.listen.port", 7650)); + I2PControlController.clearListeners(); + I2PControlController.replaceListener(ssl); + } catch (Exception e2){ + _log.log(Log.CRIT, "Unable to resume server on previous listening ip." ); + } + _log.error("Client tried to set listen address to, " + newAddress.toString() + " which isn't valid.", e); + return new JSONRPC2Response( + new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), + "\"i2pcontrol.address\" has been set to an invalid address, reverting. "), req.getID()); + } + } + } else { + outParams.put("i2pcontrol.address", oldAddress); + } + } + + outParams.put("SettingsSaved", settingsSaved); + outParams.put("RestartNeeded", restartNeeded); + return new JSONRPC2Response(outParams, req.getID()); + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2ExtendedError.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2ExtendedError.java index b566b9a..a096d58 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2ExtendedError.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2ExtendedError.java @@ -72,100 +72,100 @@ import com.thetransactioncompany.jsonrpc2.JSONRPC2Error; * @author Vladimir Dzhuvinov * @version 1.16 (2010-10-04) */ -public class JSONRPC2ExtendedError extends JSONRPC2Error { - - private static final long serialVersionUID = -6574632977222371077L; +public class JSONRPC2ExtendedError extends JSONRPC2Error { - /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ - public static final JSONRPC2Error INVALID_PASSWORD = new JSONRPC2ExtendedError(-32001, "Invalid password provided."); + private static final long serialVersionUID = -6574632977222371077L; - /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ - public static final JSONRPC2Error NO_TOKEN = new JSONRPC2ExtendedError(-32002, "No authentication token presented."); + /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ + public static final JSONRPC2Error INVALID_PASSWORD = new JSONRPC2ExtendedError(-32001, "Invalid password provided."); - /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ - public static final JSONRPC2Error INVALID_TOKEN = new JSONRPC2ExtendedError(-32003, "Authentication token doesn't exist."); + /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ + public static final JSONRPC2Error NO_TOKEN = new JSONRPC2ExtendedError(-32002, "No authentication token presented."); - /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ - public static final JSONRPC2Error TOKEN_EXPIRED = new JSONRPC2ExtendedError(-32004, "Provided authentication token was expired and will be removed."); - - /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ - public static final JSONRPC2Error UNSPECIFIED_API_VERSION = new JSONRPC2ExtendedError(-32005, "The version of the I2PControl API wasn't specified, but is required to be specified."); - - /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ - public static final JSONRPC2Error UNSUPPORTED_API_VERSION = new JSONRPC2ExtendedError(-32006, "The version of the I2PControl API specified is not supported by I2PControl."); + /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ + public static final JSONRPC2Error INVALID_TOKEN = new JSONRPC2ExtendedError(-32003, "Authentication token doesn't exist."); - - - /** - * Creates a new JSON-RPC 2.0 error with the specified code and - * message. The optional data is omitted. - * - * @param code The error code (standard pre-defined or - * application-specific). - * @param message The error message. - */ - public JSONRPC2ExtendedError(int code, String message) { - super(code, message); - } - - - /** - * Creates a new JSON-RPC 2.0 error with the specified code, - * message and data. - * - * @param code The error code (standard pre-defined or - * application-specific). - * @param message The error message. - * @param data Optional error data, must map - * to a valid JSON type. - */ - public JSONRPC2ExtendedError(int code, String message, Object data) { - super(code, message, data); - } - - - /** - * Gets the JSON-RPC 2.0 error code. - * - * @return The error code. - */ - public int getCode() { - return code; - } - - - /** - * Gets the JSON-RPC 2.0 error data. - * - * @return The error data, {@code null} if none was specified. - */ - public Object getData() { - return data; - } - - - /** - * Gets a JSON representation of the JSON-RPC 2.0 error. - * - * @return A JSON object representing this error object. - */ - public JSONObject toJSON() { - JSONObject out = new JSONObject(); - - out.put("code", code); - out.put("message", super.getMessage()); - if (data != null) - out.put("data", data); - return out; - } - - - /** - * Serialises the error object to a JSON string. - * - * @return A JSON-encoded string representing this error object. - */ - public String toString() { - return toJSON().toString(); - } + /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ + public static final JSONRPC2Error TOKEN_EXPIRED = new JSONRPC2ExtendedError(-32004, "Provided authentication token was expired and will be removed."); + + /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ + public static final JSONRPC2Error UNSPECIFIED_API_VERSION = new JSONRPC2ExtendedError(-32005, "The version of the I2PControl API wasn't specified, but is required to be specified."); + + /** Invalid JSON-RPC 2.0, implementation defined error (-32099 .. -32000) */ + public static final JSONRPC2Error UNSUPPORTED_API_VERSION = new JSONRPC2ExtendedError(-32006, "The version of the I2PControl API specified is not supported by I2PControl."); + + + + /** + * Creates a new JSON-RPC 2.0 error with the specified code and + * message. The optional data is omitted. + * + * @param code The error code (standard pre-defined or + * application-specific). + * @param message The error message. + */ + public JSONRPC2ExtendedError(int code, String message) { + super(code, message); + } + + + /** + * Creates a new JSON-RPC 2.0 error with the specified code, + * message and data. + * + * @param code The error code (standard pre-defined or + * application-specific). + * @param message The error message. + * @param data Optional error data, must map + * to a valid JSON type. + */ + public JSONRPC2ExtendedError(int code, String message, Object data) { + super(code, message, data); + } + + + /** + * Gets the JSON-RPC 2.0 error code. + * + * @return The error code. + */ + public int getCode() { + return code; + } + + + /** + * Gets the JSON-RPC 2.0 error data. + * + * @return The error data, {@code null} if none was specified. + */ + public Object getData() { + return data; + } + + + /** + * Gets a JSON representation of the JSON-RPC 2.0 error. + * + * @return A JSON object representing this error object. + */ + public JSONObject toJSON() { + JSONObject out = new JSONObject(); + + out.put("code", code); + out.put("message", super.getMessage()); + if (data != null) + out.put("data", data); + return out; + } + + + /** + * Serialises the error object to a JSON string. + * + * @return A JSON-encoded string representing this error object. + */ + public String toString() { + return toJSON().toString(); + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2Helper.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2Helper.java index e732fdb..b56d91a 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2Helper.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/JSONRPC2Helper.java @@ -29,80 +29,79 @@ import com.thetransactioncompany.jsonrpc2.JSONRPC2Request; */ public class JSONRPC2Helper { - public final static Boolean USE_NO_AUTH = false; - public final static Boolean USE_AUTH = true; - - /** - * Check incoming request for required arguments, to make sure they are valid. - * @param requiredArgs - Array of names of required arguments. If null don't check for any parameters. - * @param req - Incoming JSONRPC2 request - * @param useAuth - If true, will validate authentication token. - * @return - null if no errors were found. Corresponding JSONRPC2Error if error is found. - */ - public static JSONRPC2Error validateParams(String[] requiredArgs, JSONRPC2Request req, Boolean useAuth){ - - // Error on unnamed parameters - if (req.getParamsType() != JSONRPC2ParamsType.OBJECT){ - return JSONRPC2Error.INVALID_PARAMS; - } - HashMap params = (HashMap) req.getParams(); - - // Validate authentication token. - if (useAuth){ - JSONRPC2Error err = validateToken(params); - if (err != null){ - return err; - } - } - - // If there exist any required arguments. - if (requiredArgs != null && requiredArgs.length > 0){ - String missingArgs = ""; - for (int i = 0; i < requiredArgs.length; i++){ - if (!params.containsKey(requiredArgs[i])){ - missingArgs = missingArgs.concat(requiredArgs[i] + ","); - } - } - if (missingArgs.length() > 0){ - missingArgs = missingArgs.substring(0, missingArgs.length()-1); - return new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), "Missing parameter(s): " + missingArgs); - } - } - return null; - } - - /** - * Check incoming request for required arguments, to make sure they are valid. Will authenticate req. - * @param requiredArgs - Array of names of required arguments. If null don't check for any parameters. - * @param req - Incoming JSONRPC2 request - * @return - null if no errors were found. Corresponding JSONRPC2Error if error is found. - */ - public static JSONRPC2Error validateParams(String[] requiredArgs, JSONRPC2Request req){ - return validateParams(requiredArgs, req, JSONRPC2Helper.USE_AUTH); - } - - - - /** - * Will check incoming parameters to make sure they contain a valid token. - * @param req - Parameters of incoming request - * @return null if everything is fine, JSONRPC2Error for any corresponding error. - */ - private static JSONRPC2Error validateToken(HashMap params){ - String tokenID = (String) params.get("Token"); - if (tokenID == null){ - return JSONRPC2ExtendedError.NO_TOKEN; - } - try { - SecurityManager.getInstance().verifyToken(tokenID); - } catch (InvalidAuthTokenException e){ - return JSONRPC2ExtendedError.INVALID_TOKEN; - } catch (ExpiredAuthTokenException e){ - JSONRPC2Error err = new JSONRPC2ExtendedError(JSONRPC2ExtendedError.TOKEN_EXPIRED.getCode(), - "Provided authentication token expired "+e.getExpirytime()+", will be removed."); - return err; - } - return null; - } - + public final static Boolean USE_NO_AUTH = false; + public final static Boolean USE_AUTH = true; + + /** + * Check incoming request for required arguments, to make sure they are valid. + * @param requiredArgs - Array of names of required arguments. If null don't check for any parameters. + * @param req - Incoming JSONRPC2 request + * @param useAuth - If true, will validate authentication token. + * @return - null if no errors were found. Corresponding JSONRPC2Error if error is found. + */ + public static JSONRPC2Error validateParams(String[] requiredArgs, JSONRPC2Request req, Boolean useAuth){ + + // Error on unnamed parameters + if (req.getParamsType() != JSONRPC2ParamsType.OBJECT){ + return JSONRPC2Error.INVALID_PARAMS; + } + HashMap params = (HashMap) req.getParams(); + + // Validate authentication token. + if (useAuth){ + JSONRPC2Error err = validateToken(params); + if (err != null){ + return err; + } + } + + // If there exist any required arguments. + if (requiredArgs != null && requiredArgs.length > 0){ + String missingArgs = ""; + for (int i = 0; i < requiredArgs.length; i++){ + if (!params.containsKey(requiredArgs[i])){ + missingArgs = missingArgs.concat(requiredArgs[i] + ","); + } + } + if (missingArgs.length() > 0){ + missingArgs = missingArgs.substring(0, missingArgs.length()-1); + return new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), "Missing parameter(s): " + missingArgs); + } + } + return null; + } + + /** + * Check incoming request for required arguments, to make sure they are valid. Will authenticate req. + * @param requiredArgs - Array of names of required arguments. If null don't check for any parameters. + * @param req - Incoming JSONRPC2 request + * @return - null if no errors were found. Corresponding JSONRPC2Error if error is found. + */ + public static JSONRPC2Error validateParams(String[] requiredArgs, JSONRPC2Request req){ + return validateParams(requiredArgs, req, JSONRPC2Helper.USE_AUTH); + } + + + + /** + * Will check incoming parameters to make sure they contain a valid token. + * @param req - Parameters of incoming request + * @return null if everything is fine, JSONRPC2Error for any corresponding error. + */ + private static JSONRPC2Error validateToken(HashMap params){ + String tokenID = (String) params.get("Token"); + if (tokenID == null){ + return JSONRPC2ExtendedError.NO_TOKEN; + } + try { + SecurityManager.getInstance().verifyToken(tokenID); + } catch (InvalidAuthTokenException e){ + return JSONRPC2ExtendedError.INVALID_TOKEN; + } catch (ExpiredAuthTokenException e){ + JSONRPC2Error err = new JSONRPC2ExtendedError(JSONRPC2ExtendedError.TOKEN_EXPIRED.getCode(), + "Provided authentication token expired "+e.getExpirytime()+", will be removed."); + return err; + } + return null; + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/NetworkSettingHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/NetworkSettingHandler.java index e430af6..610ac47 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/NetworkSettingHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/NetworkSettingHandler.java @@ -44,250 +44,249 @@ public class NetworkSettingHandler implements RequestHandler { private static final int BW_BURST_TIME = 20; 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())){ - System.out.println("NTCP: " + oldNTCPPort + "->" + inParam); - _context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT, inParam); - _context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT, "false"); // Duplicate below in setProperty to make sure it is properly set. - _context.setProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT, "false"); // - restartNeeded = true; - } - settingsSaved = true; - } else{ - String sAutoPort = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT, "true"); - boolean oldAutoPort = "true".equalsIgnoreCase(sAutoPort); - if (oldAutoPort){ - String oldSSUPort = "" + _context.getProperty(UDPTransport.PROP_INTERNAL_PORT, UDPTransport.DEFAULT_INTERNAL_PORT); - outParams.put("i2p.router.net.ntcp.port", oldSSUPort); - } 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_INTERNAL_PORT, UDPTransport.DEFAULT_INTERNAL_PORT); - if ((inParam = (String) inParams.get("i2p.router.net.ssu.port")) != null){ - if (oldSSUPort== null || !oldSSUPort.equals(inParam.trim())){ - System.out.println("UDP: " + oldSSUPort + "->" + inParam); - _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; - Integer burstSize = (burstRate * BW_BURST_TIME); - if (oldBWIn == null || !oldBWIn.equals(rate.toString())){ - _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH, rate.toString()); - _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BURST_BANDWIDTH, burstRate.toString()); - _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH_PEAK, burstSize.toString()); - _context.bandwidthLimiter().reinitialize(); - } - 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; - Integer burstSize = (burstRate * BW_BURST_TIME); - if (oldBWOut == null || !oldBWOut.equals(rate.toString())){ - _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH, rate.toString()); - _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BURST_BANDWIDTH, burstRate.toString()); - _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH_PEAK, burstSize.toString()); - _context.bandwidthLimiter().reinitialize(); - } - 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); - } - } - - if (settingsSaved) - _context.router().saveConfig(); - - outParams.put("SettingsSaved", settingsSaved); - outParams.put("RestartNeeded", restartNeeded); - return new JSONRPC2Response(outParams, req.getID()); - } + 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())){ + System.out.println("NTCP: " + oldNTCPPort + "->" + inParam); + _context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT, inParam); + _context.router().setConfigSetting(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT, "false"); // Duplicate below in setProperty to make sure it is properly set. + _context.setProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT, "false"); // + restartNeeded = true; + } + settingsSaved = true; + } else{ + String sAutoPort = _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_AUTO_PORT, "true"); + boolean oldAutoPort = "true".equalsIgnoreCase(sAutoPort); + if (oldAutoPort){ + String oldSSUPort = "" + _context.getProperty(UDPTransport.PROP_INTERNAL_PORT, UDPTransport.DEFAULT_INTERNAL_PORT); + outParams.put("i2p.router.net.ntcp.port", oldSSUPort); + } 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_INTERNAL_PORT, UDPTransport.DEFAULT_INTERNAL_PORT); + if ((inParam = (String) inParams.get("i2p.router.net.ssu.port")) != null){ + if (oldSSUPort== null || !oldSSUPort.equals(inParam.trim())){ + System.out.println("UDP: " + oldSSUPort + "->" + inParam); + _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; + Integer burstSize = (burstRate * BW_BURST_TIME); + if (oldBWIn == null || !oldBWIn.equals(rate.toString())){ + _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH, rate.toString()); + _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BURST_BANDWIDTH, burstRate.toString()); + _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_INBOUND_BANDWIDTH_PEAK, burstSize.toString()); + _context.bandwidthLimiter().reinitialize(); + } + 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; + Integer burstSize = (burstRate * BW_BURST_TIME); + if (oldBWOut == null || !oldBWOut.equals(rate.toString())){ + _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH, rate.toString()); + _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BURST_BANDWIDTH, burstRate.toString()); + _context.router().setConfigSetting(FIFOBandwidthRefiller.PROP_OUTBOUND_BANDWIDTH_PEAK, burstSize.toString()); + _context.bandwidthLimiter().reinitialize(); + } + 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); + } + } + + if (settingsSaved) + _context.router().saveConfig(); + + outParams.put("SettingsSaved", settingsSaved); + outParams.put("RestartNeeded", restartNeeded); + return new JSONRPC2Response(outParams, req.getID()); + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterInfoHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterInfoHandler.java index 0a99d5d..acf2d2b 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterInfoHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterInfoHandler.java @@ -46,179 +46,179 @@ import com.thetransactioncompany.jsonrpc2.server.RequestHandler; */ public class RouterInfoHandler implements RequestHandler { - private static RouterContext _context; - private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(RouterInfoHandler.class); + private static RouterContext _context; + private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(RouterInfoHandler.class); - static { - try { - _context = RouterManager.getRouterContext(); - } catch (Exception e) { - _log.error("Unable to initialize RouterContext.", e); - } - } + 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[] { "RouterInfo" }; - } + // Reports the method names of the handled requests + public String[] handledRequests() { + return new String[] { "RouterInfo" }; + } - // Processes the requests - public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { - if (req.getMethod().equals("RouterInfo")) { - return process(req); - } else { - // Method name not supported - return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, - req.getID()); - } - } + // Processes the requests + public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { + if (req.getMethod().equals("RouterInfo")) { + return process(req); + } else { + // Method name not supported + return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, + req.getID()); + } + } - @SuppressWarnings("unchecked") - private JSONRPC2Response process(JSONRPC2Request req) { - JSONRPC2Error err = JSONRPC2Helper.validateParams(null, req); - if (err != null) - return new JSONRPC2Response(err, req.getID()); + @SuppressWarnings("unchecked") + 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(); + 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(); - if (inParams.containsKey("i2p.router.version")) { - try { - Class rvClass = Class.forName("net.i2p.router.RouterVersion"); - java.lang.reflect.Field field = rvClass.getDeclaredField("FULL_VERSION"); - String fullVersion = (String) field.get(new RouterVersion()); - outParams.put("i2p.router.version", fullVersion); - } catch (Exception e){} // Ignore - } + if (inParams.containsKey("i2p.router.version")) { + try { + Class rvClass = Class.forName("net.i2p.router.RouterVersion"); + java.lang.reflect.Field field = rvClass.getDeclaredField("FULL_VERSION"); + String fullVersion = (String) field.get(new RouterVersion()); + outParams.put("i2p.router.version", fullVersion); + } catch (Exception e){} // Ignore + } - if (inParams.containsKey("i2p.router.uptime")) { - Router router = _context.router(); - if (router == null) { - outParams.put("i2p.router.uptime", 0); - } else { - outParams.put("i2p.router.uptime", router.getUptime()); - } - } - - if (inParams.containsKey("i2p.router.status")) { - outParams.put("i2p.router.status", _context.throttle().getTunnelStatus()); - } + if (inParams.containsKey("i2p.router.uptime")) { + Router router = _context.router(); + if (router == null) { + outParams.put("i2p.router.uptime", 0); + } else { + outParams.put("i2p.router.uptime", router.getUptime()); + } + } - if (inParams.containsKey("i2p.router.net.status")) { - outParams.put("i2p.router.net.status", getNetworkStatus().ordinal()); - } - - if (inParams.containsKey("i2p.router.net.bw.inbound.1s")) { - outParams.put("i2p.router.net.bw.inbound.1s", _context.bandwidthLimiter().getReceiveBps()); - } - - if (inParams.containsKey("i2p.router.net.bw.outbound.1s")) { - outParams.put("i2p.router.net.bw.outbound.1s", _context.bandwidthLimiter().getSendBps()); - } - - if (inParams.containsKey("i2p.router.net.bw.inbound.15s")) { - outParams.put("i2p.router.net.bw.inbound.15s", _context.bandwidthLimiter().getReceiveBps15s()); - } - - if (inParams.containsKey("i2p.router.net.bw.outbound.15s")) { - outParams.put("i2p.router.net.bw.outbound.15s", _context.bandwidthLimiter().getSendBps15s()); - } - - if (inParams.containsKey("i2p.router.net.tunnels.participating")) { - outParams.put("i2p.router.net.tunnels.participating", _context.tunnelManager().getParticipatingCount()); - } - - if (inParams.containsKey("i2p.router.netdb.knownpeers")) { - // Why max(-1, 0) is used I don't know, it is the implementation used in the router console. - outParams.put("i2p.router.netdb.knownpeers", Math.max(_context.netDb().getKnownRouters()-1,0)); - } - - if (inParams.containsKey("i2p.router.netdb.activepeers")) { - outParams.put("i2p.router.netdb.activepeers", _context.commSystem().countActivePeers()); - } - - if (inParams.containsKey("i2p.router.netdb.fastpeers")) { - outParams.put("i2p.router.netdb.fastpeers", _context.profileOrganizer().countFastPeers()); - } - - if (inParams.containsKey("i2p.router.netdb.highcapacitypeers")) { - outParams.put("i2p.router.netdb.highcapacitypeers", _context.profileOrganizer().countHighCapacityPeers()); - } - - if (inParams.containsKey("i2p.router.netdb.isreseeding")) { - outParams.put("i2p.router.netdb.isreseeding", Boolean.valueOf(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress")).booleanValue()); - } - return new JSONRPC2Response(outParams, req.getID()); - } + if (inParams.containsKey("i2p.router.status")) { + outParams.put("i2p.router.status", _context.throttle().getTunnelStatus()); + } - private static enum NETWORK_STATUS{ - OK, - TESTING, - FIREWALLED, - HIDDEN, - WARN_FIREWALLED_AND_FAST, - WARN_FIREWALLED_AND_FLOODFILL, - WARN_FIREWALLED_WITH_INBOUND_TCP, - WARN_FIREWALLED_WITH_UDP_DISABLED, - ERROR_I2CP, - ERROR_CLOCK_SKEW, - ERROR_PRIVATE_TCP_ADDRESS, - ERROR_SYMMETRIC_NAT, - ERROR_UDP_PORT_IN_USE, - ERROR_NO_ACTIVE_PEERS_CHECK_CONNECTION_AND_FIREWALL, - ERROR_UDP_DISABLED_AND_TCP_UNSET, - }; - - // Ripped out of SummaryHelper.java - private NETWORK_STATUS getNetworkStatus() { - if (_context.router().getUptime() > 60 * 1000 - && (!_context.router().gracefulShutdownInProgress()) - && !_context.clientManager().isAlive()) - return (NETWORK_STATUS.ERROR_I2CP); - long skew = _context.commSystem().getFramedAveragePeerClockSkew(33); - // Display the actual skew, not the offset - if (Math.abs(skew) > 60 * 1000) - return NETWORK_STATUS.ERROR_CLOCK_SKEW; - if (_context.router().isHidden()) - return (NETWORK_STATUS.HIDDEN); + if (inParams.containsKey("i2p.router.net.status")) { + outParams.put("i2p.router.net.status", getNetworkStatus().ordinal()); + } - int status = _context.commSystem().getReachabilityStatus(); - switch (status) { - case CommSystemFacade.STATUS_OK: - RouterAddress ra = _context.router().getRouterInfo().getTargetAddress("NTCP"); - if (ra == null || (new NTCPAddress(ra)).isPubliclyRoutable()) - return NETWORK_STATUS.OK; - return NETWORK_STATUS.ERROR_PRIVATE_TCP_ADDRESS; - case CommSystemFacade.STATUS_DIFFERENT: - return NETWORK_STATUS.ERROR_SYMMETRIC_NAT; - case CommSystemFacade.STATUS_REJECT_UNSOLICITED: - if (_context.router().getRouterInfo().getTargetAddress("NTCP") != null) - return NETWORK_STATUS.WARN_FIREWALLED_WITH_INBOUND_TCP; - if (((FloodfillNetworkDatabaseFacade) _context.netDb()).floodfillEnabled()) - return NETWORK_STATUS.WARN_FIREWALLED_AND_FLOODFILL; - if (_context.router().getRouterInfo().getCapabilities().indexOf('O') >= 0) - return NETWORK_STATUS.WARN_FIREWALLED_AND_FAST; - return NETWORK_STATUS.FIREWALLED; - case CommSystemFacade.STATUS_HOSED: - return NETWORK_STATUS.ERROR_UDP_PORT_IN_USE; - case CommSystemFacade.STATUS_UNKNOWN: // fallthrough - default: - ra = _context.router().getRouterInfo().getTargetAddress("SSU"); - if (ra == null && _context.router().getUptime() > 5 * 60 * 1000) { - if (_context.commSystem().countActivePeers() <= 0) - return NETWORK_STATUS.ERROR_NO_ACTIVE_PEERS_CHECK_CONNECTION_AND_FIREWALL; - else if (_context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME) == null || _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT) == null) - return NETWORK_STATUS.ERROR_UDP_DISABLED_AND_TCP_UNSET; - else - return NETWORK_STATUS.WARN_FIREWALLED_WITH_UDP_DISABLED; - } - return NETWORK_STATUS.TESTING; - } - } + if (inParams.containsKey("i2p.router.net.bw.inbound.1s")) { + outParams.put("i2p.router.net.bw.inbound.1s", _context.bandwidthLimiter().getReceiveBps()); + } + + if (inParams.containsKey("i2p.router.net.bw.outbound.1s")) { + outParams.put("i2p.router.net.bw.outbound.1s", _context.bandwidthLimiter().getSendBps()); + } + + if (inParams.containsKey("i2p.router.net.bw.inbound.15s")) { + outParams.put("i2p.router.net.bw.inbound.15s", _context.bandwidthLimiter().getReceiveBps15s()); + } + + if (inParams.containsKey("i2p.router.net.bw.outbound.15s")) { + outParams.put("i2p.router.net.bw.outbound.15s", _context.bandwidthLimiter().getSendBps15s()); + } + + if (inParams.containsKey("i2p.router.net.tunnels.participating")) { + outParams.put("i2p.router.net.tunnels.participating", _context.tunnelManager().getParticipatingCount()); + } + + if (inParams.containsKey("i2p.router.netdb.knownpeers")) { + // Why max(-1, 0) is used I don't know, it is the implementation used in the router console. + outParams.put("i2p.router.netdb.knownpeers", Math.max(_context.netDb().getKnownRouters()-1,0)); + } + + if (inParams.containsKey("i2p.router.netdb.activepeers")) { + outParams.put("i2p.router.netdb.activepeers", _context.commSystem().countActivePeers()); + } + + if (inParams.containsKey("i2p.router.netdb.fastpeers")) { + outParams.put("i2p.router.netdb.fastpeers", _context.profileOrganizer().countFastPeers()); + } + + if (inParams.containsKey("i2p.router.netdb.highcapacitypeers")) { + outParams.put("i2p.router.netdb.highcapacitypeers", _context.profileOrganizer().countHighCapacityPeers()); + } + + if (inParams.containsKey("i2p.router.netdb.isreseeding")) { + outParams.put("i2p.router.netdb.isreseeding", Boolean.valueOf(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress")).booleanValue()); + } + return new JSONRPC2Response(outParams, req.getID()); + } + + private static enum NETWORK_STATUS{ + OK, + TESTING, + FIREWALLED, + HIDDEN, + WARN_FIREWALLED_AND_FAST, + WARN_FIREWALLED_AND_FLOODFILL, + WARN_FIREWALLED_WITH_INBOUND_TCP, + WARN_FIREWALLED_WITH_UDP_DISABLED, + ERROR_I2CP, + ERROR_CLOCK_SKEW, + ERROR_PRIVATE_TCP_ADDRESS, + ERROR_SYMMETRIC_NAT, + ERROR_UDP_PORT_IN_USE, + ERROR_NO_ACTIVE_PEERS_CHECK_CONNECTION_AND_FIREWALL, + ERROR_UDP_DISABLED_AND_TCP_UNSET, + }; + + // Ripped out of SummaryHelper.java + private NETWORK_STATUS getNetworkStatus() { + if (_context.router().getUptime() > 60 * 1000 + && (!_context.router().gracefulShutdownInProgress()) + && !_context.clientManager().isAlive()) + return (NETWORK_STATUS.ERROR_I2CP); + long skew = _context.commSystem().getFramedAveragePeerClockSkew(33); + // Display the actual skew, not the offset + if (Math.abs(skew) > 60 * 1000) + return NETWORK_STATUS.ERROR_CLOCK_SKEW; + if (_context.router().isHidden()) + return (NETWORK_STATUS.HIDDEN); + + int status = _context.commSystem().getReachabilityStatus(); + switch (status) { + case CommSystemFacade.STATUS_OK: + RouterAddress ra = _context.router().getRouterInfo().getTargetAddress("NTCP"); + if (ra == null || (new NTCPAddress(ra)).isPubliclyRoutable()) + return NETWORK_STATUS.OK; + return NETWORK_STATUS.ERROR_PRIVATE_TCP_ADDRESS; + case CommSystemFacade.STATUS_DIFFERENT: + return NETWORK_STATUS.ERROR_SYMMETRIC_NAT; + case CommSystemFacade.STATUS_REJECT_UNSOLICITED: + if (_context.router().getRouterInfo().getTargetAddress("NTCP") != null) + return NETWORK_STATUS.WARN_FIREWALLED_WITH_INBOUND_TCP; + if (((FloodfillNetworkDatabaseFacade) _context.netDb()).floodfillEnabled()) + return NETWORK_STATUS.WARN_FIREWALLED_AND_FLOODFILL; + if (_context.router().getRouterInfo().getCapabilities().indexOf('O') >= 0) + return NETWORK_STATUS.WARN_FIREWALLED_AND_FAST; + return NETWORK_STATUS.FIREWALLED; + case CommSystemFacade.STATUS_HOSED: + return NETWORK_STATUS.ERROR_UDP_PORT_IN_USE; + case CommSystemFacade.STATUS_UNKNOWN: // fallthrough + default: + ra = _context.router().getRouterInfo().getTargetAddress("SSU"); + if (ra == null && _context.router().getUptime() > 5 * 60 * 1000) { + if (_context.commSystem().countActivePeers() <= 0) + return NETWORK_STATUS.ERROR_NO_ACTIVE_PEERS_CHECK_CONNECTION_AND_FIREWALL; + else if (_context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_HOSTNAME) == null || _context.getProperty(CommSystemFacadeImpl.PROP_I2NP_NTCP_PORT) == null) + return NETWORK_STATUS.ERROR_UDP_DISABLED_AND_TCP_UNSET; + else + return NETWORK_STATUS.WARN_FIREWALLED_WITH_UDP_DISABLED; + } + return NETWORK_STATUS.TESTING; + } + } } diff --git a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterManagerHandler.java b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterManagerHandler.java index b9d73f1..dd530a6 100644 --- a/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterManagerHandler.java +++ b/src/java/net/i2p/i2pcontrol/servlets/jsonrpc2handlers/RouterManagerHandler.java @@ -49,121 +49,121 @@ import com.thetransactioncompany.jsonrpc2.server.RequestHandler; */ public class RouterManagerHandler implements RequestHandler { - private static RouterContext _context; - private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(RouterManagerHandler.class); - - private final static int SHUTDOWN_WAIT = 1500; + private static RouterContext _context; + private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(RouterManagerHandler.class); - static { - try { - _context = RouterManager.getRouterContext(); - } catch (Exception e) { - _log.error("Unable to initialize RouterContext.", e); - } - } + private final static int SHUTDOWN_WAIT = 1500; - // Reports the method names of the handled requests - public String[] handledRequests() { - return new String[] { "RouterManager" }; - } + static { + try { + _context = RouterManager.getRouterContext(); + } catch (Exception e) { + _log.error("Unable to initialize RouterContext.", e); + } + } - // Processes the requests - public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { - if (req.getMethod().equals("RouterManager")) { - return process(req); - } else { - // Method name not supported - return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, - req.getID()); - } - } + // Reports the method names of the handled requests + public String[] handledRequests() { + return new String[] { "RouterManager" }; + } - private JSONRPC2Response process(JSONRPC2Request req) { - JSONRPC2Error err = JSONRPC2Helper.validateParams(null, req); - if (err != null) - return new JSONRPC2Response(err, req.getID()); + // Processes the requests + public JSONRPC2Response process(JSONRPC2Request req, MessageContext ctx) { + if (req.getMethod().equals("RouterManager")) { + return process(req); + } else { + // Method name not supported + return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, + 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(); + 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(); + + if (inParams.containsKey("Shutdown")) { + outParams.put("Shutdown", null); + (new Thread(){ + @Override + public void run(){ + try { + Thread.sleep(SHUTDOWN_WAIT); + } catch (InterruptedException e) {} + _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_HARD)); + _context.router().shutdown(Router.EXIT_HARD); } + }).start(); + return new JSONRPC2Response(outParams, req.getID()); + } + + if (inParams.containsKey("Restart")) { + outParams.put("Restart", null); + (new Thread(){ + @Override + public void run(){ + try { + Thread.sleep(SHUTDOWN_WAIT); + } catch (InterruptedException e) {} + _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_HARD_RESTART)); + _context.router().shutdown(Router.EXIT_HARD_RESTART); + } + }).start(); + return new JSONRPC2Response(outParams, req.getID()); + } + + if (inParams.containsKey("ShutdownGraceful")) { + outParams.put("ShutdownGraceful", null); + (new Thread(){ + @Override + public void run(){ + try { + Thread.sleep(SHUTDOWN_WAIT); + } catch (InterruptedException e) {} + _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_GRACEFUL)); + _context.router().shutdownGracefully(); + } + }).start(); + return new JSONRPC2Response(outParams, req.getID()); + } + + if (inParams.containsKey("RestartGraceful")) { + outParams.put("RestartGraceful", null); + (new Thread(){ + @Override + public void run(){ + try { + Thread.sleep(SHUTDOWN_WAIT); + } catch (InterruptedException e) {} + _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_GRACEFUL_RESTART)); + _context.router().shutdownGracefully(Router.EXIT_GRACEFUL_RESTART); } + }).start(); + return new JSONRPC2Response(outParams, req.getID()); + } + + if (inParams.containsKey("Reseed")){ + outParams.put("Reseed", null); + (new Thread(){ + @Override + public void run(){ + ReseedChecker reseeder = new ReseedChecker(_context); + reseeder.requestReseed(); + } + }).start(); + } + + return new JSONRPC2Response(outParams, req.getID()); + } - if (inParams.containsKey("Shutdown")) { - outParams.put("Shutdown", null); - (new Thread(){ - @Override - public void run(){ - try { - Thread.sleep(SHUTDOWN_WAIT); - } catch (InterruptedException e) {} - _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_HARD)); - _context.router().shutdown(Router.EXIT_HARD); } - }).start(); - return new JSONRPC2Response(outParams, req.getID()); - } - - if (inParams.containsKey("Restart")) { - outParams.put("Restart", null); - (new Thread(){ - @Override - public void run(){ - try { - Thread.sleep(SHUTDOWN_WAIT); - } catch (InterruptedException e) {} - _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_HARD_RESTART)); - _context.router().shutdown(Router.EXIT_HARD_RESTART); - } - }).start(); - return new JSONRPC2Response(outParams, req.getID()); - } - - if (inParams.containsKey("ShutdownGraceful")) { - outParams.put("ShutdownGraceful", null); - (new Thread(){ - @Override - public void run(){ - try { - Thread.sleep(SHUTDOWN_WAIT); - } catch (InterruptedException e) {} - _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_GRACEFUL)); - _context.router().shutdownGracefully(); - } - }).start(); - return new JSONRPC2Response(outParams, req.getID()); - } - - if (inParams.containsKey("RestartGraceful")) { - outParams.put("RestartGraceful", null); - (new Thread(){ - @Override - public void run(){ - try { - Thread.sleep(SHUTDOWN_WAIT); - } catch (InterruptedException e) {} - _context.addShutdownTask(new UpdateWrapperManagerTask(Router.EXIT_GRACEFUL_RESTART)); - _context.router().shutdownGracefully(Router.EXIT_GRACEFUL_RESTART); } - }).start(); - return new JSONRPC2Response(outParams, req.getID()); - } - - if (inParams.containsKey("Reseed")){ - outParams.put("Reseed", null); - (new Thread(){ - @Override - public void run(){ - ReseedChecker reseeder = new ReseedChecker(_context); - reseeder.requestReseed(); - } - }).start(); - } - - return new JSONRPC2Response(outParams, req.getID()); - } - public static class UpdateWrapperManagerTask implements Runnable { private int _exitCode; public UpdateWrapperManagerTask(int exitCode) {