java.lang.Object
net.i2p.router.Router
All Implemented Interfaces:
RouterClock.ClockShiftListener

public class Routerextends Object implements RouterClock.ClockShiftListener
Core router implementation that manages I2P node lifecycle, configuration, and subsystem coordination. Handles startup/shutdown, router info management, bandwidth capabilities, and provides the main entry point for both embedded and standalone router operation.

For embedded use, instantiate, call setKillVMOnEnd(false), and then call runRouter().

  • Field Details

    • _log

      private Log _log
      Logger for the router.
    • _context

      private final RouterContext _context
      The router context.
    • _config

      private final Map<String,String> _config
      The router's config properties.
    • _configFilename

      private String _configFilename
      Full path to the config file.
    • _routerInfo

      private RouterInfo _routerInfo
      Our router info, null until we have one.
    • _routerInfoLock

      private final ReentrantReadWriteLock _routerInfoLock
      Lock guarding the router info.
    • _routerIdent

      private RouterIdentity _routerIdent
      Our router identity.
    • _routerHash

      private Hash _routerHash
      Hash of our router identity.
    • routerInfoFileLock

      public final Object routerInfoFileLock
      Not for external use.
    • _configFileLock

      private final Object _configFileLock
      Lock guarding writes to router.config.
    • _started

      private long _started
      When the router was started.
    • _killVMOnEnd

      private volatile boolean _killVMOnEnd
      Whether shutdown exits the JVM.
    • _gracefulExitCode

      private int _gracefulExitCode
      Exit code set before a graceful shutdown.
    • _oomListener

      private I2PThread.OOMEventListener _oomListener
      Listener notified on out-of-memory errors.
    • _shutdownHook

      private ShutdownHook _shutdownHook
      Hook run when the JVM exits.
    • _gracefulShutdownDetector

      private I2PThread _gracefulShutdownDetector
      Thread watching for a shutdown request.
    • _gracefulShutdownLock

      private Object _gracefulShutdownLock
      Lock for the shutdown request flag.
    • _watchdog

      private RouterWatchdog _watchdog
      Watchdog that restarts a hung router.
    • _watchdogThread

      private Thread _watchdogThread
      Thread running the watchdog.
    • _markLiveliness

      private MarkLiveliness _markLiveliness
      Thread touching the watchdog timestamp.
    • _eventLog

      private final EventLog _eventLog
      Log of events shown on the notifications page.
    • _stateLock

      private final Object _stateLock
      Lock guarding the router state.
    • _state

      private Router.State _state
      Current state of the router.
    • _familyKeyCrypto

      private FamilyKeyCrypto _familyKeyCrypto
      Signer for our router family, if configured.
    • _familyKeyCryptoFail

      private boolean _familyKeyCryptoFail
      Whether loading the family key failed.
    • _familyKeyLock

      public final Object _familyKeyLock
      Lock protecting the family key crypto.
    • _upnpScannerCallback

      private UPnPScannerCallback _upnpScannerCallback
      Callback logging the UPnP scan results.
    • _downtime

      private long _downtime
      How long the router was down before this run.
    • _lastCongestionCap

      private char _lastCongestionCap
      The congestion cap last logged, to skip repeat warnings.
    • _bandwidthHistory

      private BandwidthHistory _bandwidthHistory
      History of our bandwidth over time.
    • _cachedSharePctProp

      private String _cachedSharePctProp
      Config string the cached share percentage was parsed from.
    • _cachedSharePct

      private double _cachedSharePct
      Cached share of tunnels offered to clients.
    • BUNDLE_NAME

      private static final String BUNDLE_NAME
      Bundle holding the translated console strings.
      See Also:
    • PROP_CONFIG_FILE

      public static final String PROP_CONFIG_FILE
      Config property for the router config file location.
      See Also:
    • CLOCK_FUDGE_FACTOR

      public static final long CLOCK_FUDGE_FACTOR
      Let clocks be off by 30 seconds (reduced from 60s to improve lease renewal timing).
      See Also:
    • DEFAULT_NETWORK_ID

      private static final int DEFAULT_NETWORK_ID
      Used to differentiate routerInfo files on different networks.
      See Also:
    • PROP_NETWORK_ID

      private static final String PROP_NETWORK_ID
      Config key for the network id.
      See Also:
    • _networkID

      private final int _networkID
      The network id we communicate on.
    • COALESCE_TIME

      public static final int COALESCE_TIME
      Coalesce stats this often - should be a little less than one minute, so the graphs get updated.
      See Also:
    • PROP_HIDDEN

      public static final String PROP_HIDDEN
      This puts an 'H' in your routerInfo *.
      See Also:
    • PROP_HIDDEN_HIDDEN

      public static final String PROP_HIDDEN_HIDDEN
      This does not put an 'H' in your routerInfo *.
      See Also:
    • PROP_DYNAMIC_KEYS

      public static final String PROP_DYNAMIC_KEYS
      New router keys at every restart. Disabled.
      See Also:
    • PROP_REBUILD_KEYS

      public static final String PROP_REBUILD_KEYS
      New router keys once only.
      See Also:
    • PROP_SHUTDOWN_IN_PROGRESS

      private static final String PROP_SHUTDOWN_IN_PROGRESS
      See Also:
    • PROP_IB_RANDOM_KEY

      public static final String PROP_IB_RANDOM_KEY
      Config property for the inbound exploratory pool random key.
      See Also:
    • PROP_OB_RANDOM_KEY

      public static final String PROP_OB_RANDOM_KEY
      Config property for the outbound exploratory pool random key.
      See Also:
    • EVENTLOG

      private static final String EVENTLOG
      File name for the event log.
      See Also:
    • PROP_JBIGI

      private static final String PROP_JBIGI
      Config key recording the loaded jbigi resource.
      See Also:
    • PROP_JBIGI_PROCESSOR

      private static final String PROP_JBIGI_PROCESSOR
      Config key recording the processor the jbigi was chosen for.
      See Also:
    • UPDATE_FILE

      public static final String UPDATE_FILE
      The update zip file name.
      See Also:
    • CONGESTION_CAPS

      private static final boolean CONGESTION_CAPS
      Whether congestion capability letters are published.
      See Also:
    • SHUTDOWN_WAIT_SECS

      private static final int SHUTDOWN_WAIT_SECS
      Seconds allowed for a graceful shutdown.
      See Also:
    • PROP_ADVANCED

      private static final String PROP_ADVANCED
      Config key for the console's advanced mode.
      See Also:
    • PROP_RELAX_CONGESTION_CAP

      private static final String PROP_RELAX_CONGESTION_CAP
      Config key relaxing the congestion cap rules.
      See Also:
    • ORIGINAL_TIMEZONE_ID

      private static final String ORIGINAL_TIMEZONE_ID
      Timezone the router started with, restored on shutdown.
    • STATES_ALIVE

      private static final Set<Router.State> STATES_ALIVE
      For efficiency. EnumSets are bitmasks.
    • STATES_GRACEFUL

      private static final Set<Router.State> STATES_GRACEFUL
      States counted as a graceful shutdown.
    • STATES_FINAL

      private static final Set<Router.State> STATES_FINAL
      States counted as the final shutdown.
    • CAPABILITY_BW12

      public static final char CAPABILITY_BW12
      Bandwidth class capability for 12 KB/s, publicizing our ballpark capacity.
      See Also:
    • CAPABILITY_BW32

      public static final char CAPABILITY_BW32
      Bandwidth class capability for 32 KB/s.
      See Also:
    • CAPABILITY_BW64

      public static final char CAPABILITY_BW64
      Bandwidth class capability for 64 KB/s.
      See Also:
    • CAPABILITY_BW128

      public static final char CAPABILITY_BW128
      Bandwidth class capability for 128 KB/s.
      See Also:
    • CAPABILITY_BW256

      public static final char CAPABILITY_BW256
      Bandwidth class capability for 256 KB/s.
      See Also:
    • CAPABILITY_BW512

      public static final char CAPABILITY_BW512
      Bandwidth class capability for 512 KB/s.
      See Also:
    • CAPABILITY_BW_UNLIMITED

      public static final char CAPABILITY_BW_UNLIMITED
      Bandwidth class capability for unlimited bandwidth.
      See Also:
    • PROP_FORCE_BWCLASS

      public static final String PROP_FORCE_BWCLASS
      For testing.
      See Also:
    • CAPABILITY_REACHABLE

      public static final char CAPABILITY_REACHABLE
      Reachability capability.
      See Also:
    • CAPABILITY_UNREACHABLE

      public static final char CAPABILITY_UNREACHABLE
      Unreachability capability.
      See Also:
    • CAPABILITY_CONGESTION_MODERATE

      public static final char CAPABILITY_CONGESTION_MODERATE
      Congestion capability: the peer reports moderate, sustained congestion (proposal 162, alongside CAPABILITY_CONGESTION_SEVERE and CAPABILITY_NO_TUNNELS).
      See Also:
    • CAPABILITY_CONGESTION_SEVERE

      public static final char CAPABILITY_CONGESTION_SEVERE
      Congestion capability: the peer reports severe congestion, at the level where it should stop being selected for new tunnels.
      See Also:
    • CAPABILITY_NO_TUNNELS

      public static final char CAPABILITY_NO_TUNNELS
      Congestion capability: the peer reports that it is up but cannot build tunnels, so it can still serve existing ones.
      See Also:
    • PROP_FORCE_UNREACHABLE

      public static final String PROP_FORCE_UNREACHABLE
      For testing.
      See Also:
    • MIN_BW_K

      public static final int MIN_BW_K
      In binary (1024) Kbytes.
      See Also:
    • MIN_BW_L

      public static final int MIN_BW_L
      In binary (1024) Kbytes.
      See Also:
    • MIN_BW_M

      public static final int MIN_BW_M
      In binary (1024) Kbytes.
      See Also:
    • MIN_BW_N

      public static final int MIN_BW_N
      In binary (1024) Kbytes.
      See Also:
    • MIN_BW_O

      public static final int MIN_BW_O
      In binary (1024) Kbytes.
      See Also:
    • MIN_BW_P

      public static final int MIN_BW_P
      In binary (1024) Kbytes.
      See Also:
    • MIN_BW_X

      public static final int MIN_BW_X
      In binary (1024) Kbytes.
      See Also:
    • _rebuildFiles

      private static final String[] _rebuildFiles
      Ugly list of files that we need to kill if we are building a new identity.
    • EXIT_GRACEFUL

      public static final int EXIT_GRACEFUL
      Shut down after all tunnels are gone.
      See Also:
    • EXIT_HARD

      public static final int EXIT_HARD
      Shut down immediately.
      See Also:
    • EXIT_OOM

      public static final int EXIT_OOM
      Shut down immediately.
      See Also:
    • EXIT_HARD_RESTART

      public static final int EXIT_HARD_RESTART
      Shut down immediately, and tell the wrapper to restart.
      See Also:
    • EXIT_GRACEFUL_RESTART

      public static final int EXIT_GRACEFUL_RESTART
      Shut down after all tunnels are gone, and tell the wrapper to restart.
      See Also:
    • ALLOW_DYNAMIC_KEYS

      private static final boolean ALLOW_DYNAMIC_KEYS
      Disable dynamic key functionality for the moment, as it may be harmful and doesn't add meaningful anonymity.
      See Also:
    • LIVELINESS_DELAY

      private static final long LIVELINESS_DELAY
      Interval between watchdog liveliness touches, one minute.
      See Also:
    • PROP_BANDWIDTH_SHARE_PERCENTAGE

      public static final String PROP_BANDWIDTH_SHARE_PERCENTAGE
      Property naming the share of our bandwidth that tunnels may consume.
      See Also:
    • DEFAULT_SHARE_PERCENTAGE

      public static final int DEFAULT_SHARE_PERCENTAGE
      Default share, as a percentage of the configured bandwidth limits.
      See Also:
  • Constructor Details

    • Router

      public Router()
      Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.

      Config file name is "router.config" unless router.configLocation set in system properties.

      See two-arg constructor for more information.

      Throws:
      IllegalStateException - since 0.9.19 if another router with this config is running
    • Router

      public Router(Properties envProps)
      Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.

      Config file name is "router.config" unless router.configLocation set in envProps or system properties.

      See two-arg constructor for more information.

      Parameters:
      envProps - may be null
      Throws:
      IllegalStateException - since 0.9.19 if another router with this config is running
    • Router

      public Router(String configFilename)
      Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.

      See two-arg constructor for more information.

      Parameters:
      configFilename - may be null
      Throws:
      IllegalStateException - since 0.9.19 if another router with this config is running
    • Router

      public Router(String configFilename, Properties envProps)
      Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.

      If configFilename is non-null, configuration is read in from there. Else if envProps is non-null, configuration is read in from the location given in the router.configLocation property. Else it's read in from the System property router.configLocation. Else from the file "router.config".

      The most important properties are i2p.dir.base (the install directory, may be read-only) and i2p.dir.config (the user's configuration/data directory).

      i2p.dir.base defaults to user.dir (CWD) but should almost always be set.

      i2p.dir.config default depends on OS, user name (to detect if running as a service or not), and auto-detection of whether there appears to be previous data files in the base dir. See WorkingDir for details. If the config dir does not exist, it will be created, and files migrated from the base dir, in this constructor. If files in an existing config dir indicate that another router is already running with this directory, the constructor will delay for several seconds to be sure, and then throw an IllegalStateException.

      Parameters:
      configFilename - may be null
      envProps - may be null
      Throws:
      IllegalStateException - since 0.9.19 if another router with this config is running
  • Method Details

    • isAdvanced

      public boolean isAdvanced()
      Whether advanced mode is enabled.
      Returns:
      true if advanced mode is enabled
    • startupStuff

      private void startupStuff()
      Initializes the RouterContext. Starts some threads. Does not install updates. All this was in the constructor.

      Could block for 10 seconds or forever if waiting for entropy.

    • clearCaches

      public static final void clearCaches()
      Not for external use.
    • setKillVMOnEnd

      public void setKillVMOnEnd(boolean shouldDie)
      Configure the router to kill the JVM when the router shuts down, as well as whether to explicitly halt the JVM during the hard fail process.

      Defaults to true. Set to false for embedded before calling runRouter().

      Parameters:
      shouldDie - true to kill VM on shutdown, false for embedded use
    • getKillVMOnEnd

      public boolean getKillVMOnEnd()
      Check whether the router is configured to kill the JVM on shutdown.
      Returns:
      true if VM will be killed on router shutdown
    • getConfigFilename

      public String getConfigFilename()
      The absolute path to the router configuration file.
      Returns:
      absolute path to the configuration file
    • getConfigSetting

      public String getConfigSetting(String name)
      Retrieve a configuration setting by name.
      Parameters:
      name - the configuration property name
      Returns:
      the configuration value, or null if not set
    • getConfigSettings

      public Set<String> getConfigSettings()
      An unmodifiable set of all configuration property names.

      Warning: this is a live view of the configuration - use saveConfig() or saveConfig(String, String) when you modify the returned set, otherwise the router may race with a concurrent write.

      Returns:
      unmodifiable Set of configuration property names (unsorted)
    • getConfigMap

      public Map<String,String> getConfigMap()
      An unmodifiable map of all configuration settings.
      Returns:
      unmodifiable Map of configuration property names to values (unsorted)
    • getRouterInfo

      public RouterInfo getRouterInfo()
      Our current router info. Warning, may be null if called very early.

      Warning - risk of deadlock - do not call while holding locks

      Note: Due to lock contention, especially during a rebuild of the router info, this may take a long time. For determining the current status of the router, use RouterContext.commSystem()getStatus().

      Returns:
      the router info
    • getRouterIdentity

      public RouterIdentity getRouterIdentity()
      Our current router identity. Warning, may be null if called very early. Lockless.
      Returns:
      the router identity
    • getRouterHash

      public Hash getRouterHash()
      Our current router hash. Warning, may be null if called very early. Lockless.
      Returns:
      the router hash
    • setRouterInfo

      public void setRouterInfo(RouterInfo info)
      Caller must ensure info is valid - no validation done here. Not for external use.

      Warning - risk of deadlock - do not call while holding locks.

      Parameters:
      info - the router info to adopt as ours; the caller must ensure it is valid
    • getWhenStarted

      public long getWhenStarted()
      Used only by routerconsole.. to be deprecated?
      Returns:
      System time, NOT context time
    • getUptime

      public long getUptime()
      Wall clock uptime. This uses System time, NOT context time, so context clock shifts will not affect it. This is important if NTP fails and the clock then shifts from a SSU peer source just after startup.
      Returns:
      the uptime in milliseconds since the router started
    • getNetworkID

      public int getNetworkID()
      The network ID. Default 2. May be changed with the config property router.networkID (restart required). Change only if running a test network to prevent cross-network contamination.
      Returns:
      2 - 254
    • getContext

      public RouterContext getContext()
      Non-null, but take care when accessing context items before runRouter() is called as the context will not be initialized.
      Returns:
      non-null
    • setUPnPScannerCallback

      public void setUPnPScannerCallback(UPnPScannerCallback callback)
      For Android only. MUST be set before runRouter() is called.
      Parameters:
      callback - the callback or null to clear it
    • getUPnPScannerCallback

      public UPnPScannerCallback getUPnPScannerCallback()
      For Android only.
      Returns:
      the callback or null if none
    • runRouter

      public void runRouter()
      This must be called after instantiation. Starts the threads. Does not install updates. This is for embedded use. Standard standalone installation uses main(String[]) instead, which checks for updates and then calls this.

      This may take quite a while, especially if NTP fails or the system lacks entropy.

      Throws:
      IllegalStateException - if called more than once
    • readConfig

      public void readConfig()
      This updates the config with all settings found in the file. It does not clear the config first, so settings not found in the file will remain in the config.

      This is synchronized with saveConfig(). Not for external use.

    • getConfig

      private static Properties getConfig(RouterContext ctx, String filename)
      This does not use ctx.getConfigDir(), must provide a full path in filename Caller must synchronize.
      Parameters:
      ctx - will be null at startup when called from constructor
      filename - full path of the config file to read
      Returns:
      the settings read from that file, empty if the file does not exist
    • changeState

      private void changeState(Router.State state)
      Advance the router state machine, starting or stopping components as needed.
      Parameters:
      state - the new state to advance to
    • isAlive

      public boolean isAlive()
      Check if the router is alive (in startup or running state). True during initial startup, false during soft restart.
      Returns:
      true if router is in an alive state
    • isRunning

      public boolean isRunning()
      Whether the router is RUNNING, i.e. NetDB and expl. tunnels are ready.
      Returns:
      true if router is RUNNING, i.e NetDB and Expl. tunnels are ready.
    • isRestarting

      public boolean isRestarting()
      Whether the router is RESTARTING (soft restart).
      Returns:
      true if router is RESTARTING (soft restart)
    • setIsAlive

      public void setIsAlive()
      Only for Restarter, after soft restart is complete. Not for external use.
    • setNetDbReady

      public void setNetDbReady()
      Only for NetDB, after RIs are loaded. Not for external use.
    • setExplTunnelsReady

      public void setExplTunnelsReady()
      Only for Tunnel Building, after we have non-zero-hop expl. tunnels. Not for external use.
    • gracefulShutdownInProgress

      public boolean gracefulShutdownInProgress()
      Is a graceful shutdown in progress? This may be cancelled. Note that this also returns true if an uncancellable final shutdown is in progress.
      Returns:
      true while a graceful or final shutdown is running
    • isFinalShutdownInProgress

      public boolean isFinalShutdownInProgress()
      Is a final shutdown in progress? This may not be cancelled.
      Returns:
      whether final shutdown in progress
    • rebuildRouterInfo

      public void rebuildRouterInfo()
      Rebuild and republish our routerInfo since something significant has changed. This is a non-blocking rebuild.

      Not for external use.

      Warning - risk of deadlock - do not call while holding locks.

    • rebuildRouterInfo

      public void rebuildRouterInfo(boolean blockingRebuild)
      Rebuild and republish our routerInfo since something significant has changed. Not for external use.

      Warning - risk of deadlock - do not call while holding locks.

      Parameters:
      blockingRebuild - ignored, operation is always nonblocking
    • locked_rebuildRouterInfo

      private void locked_rebuildRouterInfo(List<RouterAddress> addresses)
      Rebuild and republish our routerInfo since something significant has changed.
      Parameters:
      addresses - the current router addresses to publish
    • getFamilyKeyCrypto

      public FamilyKeyCrypto getFamilyKeyCrypto()
      Family Key Crypto Signer / Verifier. Not for external use. If family key is set, first call Will take a while to generate keys. Warning - risk of deadlock - do not call while holding locks (other than routerInfoLock).
      Returns:
      null on initialization failure
    • getBandwidthClass

      public char getBandwidthClass()
      The current bandwidth class. For building our RI. Not for external use.
      Returns:
      a character to be added to the RI, one of "KLMNOPX"
    • getCapabilities

      public String getCapabilities()
      For building our RI. Not for external use.
      Returns:
      a capabilities string to be added to the RI
    • isHidden

      public boolean isHidden()
      Whether the router is hidden. This checks the config only. We don't check the current RI due to deadlocks.
      Returns:
      true if the router is hidden
    • eventLog

      public EventLog eventLog()
      The router's event log, shared with the console pages that render it.
      Returns:
      the router's event log, which the console pages render
    • killKeys

      public void killKeys()
      Not for external use.
    • rebuildNewIdentity

      public void rebuildNewIdentity()
      Rebuild a new identity the hard way - delete all of our old identity files, then reboot the router.

      Calls exit(), never returns.

      Not for external use.

    • warmupCrypto

      private void warmupCrypto()
      Could block for 10 seconds or forever.
    • shutdown

      public void shutdown(int exitCode)
      Shutdown with no chance of cancellation. Blocking, will call exit() and not return unless setKillVMOnExit(false) was previously called, or a final shutdown is already in progress. May take several seconds as it runs all the shutdown hooks.
      Parameters:
      exitCode - one of the EXIT_* values, non-negative
      Throws:
      IllegalArgumentException - if exitCode negative
    • shutdown2

      public void shutdown2(int exitCode)
      Cancel the JVM runtime hook before calling this. Called by the ShutdownHook. NOT to be called by others, use shutdown().
      Parameters:
      exitCode - one of the EXIT_* values, non-negative
      Throws:
      IllegalArgumentException - if exitCode negative
    • shutdownSubsystems

      private void shutdownSubsystems()
      Shut down all router subsystems. Error handling level depends on log verbosity: debug → full stack trace, advanced → message only, else → silent.
    • shutdownOne

      private void shutdownOne(String name, boolean debug, boolean advanced, Runnable task)
      Shut down a single subsystem, with error logging appropriate to verbosity.
      Parameters:
      name - subsystem name for logging
      debug - if true, log full stack trace on error
      advanced - if true, log message-only on error
      task - the shutdown operation
    • finalShutdown

      private void finalShutdown(int exitCode)
      Cancel the JVM runtime hook before calling this.
      Parameters:
      exitCode - one of the EXIT_* values, non-negative
    • shutdownGracefully

      public void shutdownGracefully()
      Non-blocking shutdown.

      Call this if we want the router to kill itself as soon as we aren't participating in any more tunnels (etc). This will not block and doesn't guarantee any particular time frame for shutting down. To shut the router down immediately, use shutdown(int). If you want to cancel the graceful shutdown (prior to actual shutdown ;), call cancelGracefulShutdown().

      Exit code will be EXIT_GRACEFUL.

      Shutdown delay will be from zero to 11 minutes.

    • shutdownGracefully

      public void shutdownGracefully(int exitCode)
      Non-blocking shutdown.

      Call this with EXIT_HARD or EXIT_HARD_RESTART for a non-blocking, hard, non-graceful shutdown with a brief delay to allow a UI response

      Returns silently if a final shutdown is already in progress.

      Parameters:
      exitCode - one of the EXIT_* values, non-negative
      Throws:
      IllegalArgumentException - if exitCode negative
    • cancelGracefulShutdown

      public void cancelGracefulShutdown()
      Cancel any prior request to shut the router down gracefully.

      Returns silently if a final shutdown is already in progress.

    • scheduledGracefulExitCode

      public int scheduledGracefulExitCode()
      What exit code do we plan on using when we shut down (or -1, if there isn't a graceful shutdown planned).
      Returns:
      one of the EXIT_* values or -1
    • getShutdownTimeRemaining

      public long getShutdownTimeRemaining()
      How long until the graceful shutdown will kill us?
      Returns:
      -1 if no shutdown in progress.
    • saveConfig

      public boolean saveConfig()
      Save the current config options (returning true if save was successful, false otherwise)

      Synchronized with file read in getConfig(RouterContext, String).

      Returns:
      true if the properties were written, false if the write failed
    • saveConfig

      public boolean saveConfig(String name, String value)
      Updates the current config with the given key/value and then saves it. Prevents a race in the interval between _config.put()/_config.remove() and saveConfig(), Synchronized with getConfig() / saveConfig().
      Parameters:
      name - setting to add/change/remove before saving
      value - if non-null, updated value; if null, setting will be removed
      Returns:
      true if the config file was written
    • saveConfig

      public boolean saveConfig(Map toAdd, Collection<String> toRemove)
      Updates the current config and then saves it. Prevents a race in the interval between _config.putAll()/_config.remove() and saveConfig(), Synchronized with getConfig() / saveConfig().
      Parameters:
      toAdd - settings to add/change before saving, may be null or empty
      toRemove - settings to remove before saving, may be null or empty
      Returns:
      true if the config file was written
    • clockShift

      public void clockShift(long delta)
      The clock shift listener. Restart the router if we should.
      Specified by:
      clockShift in interface RouterClock.ClockShiftListener
      Parameters:
      delta - The system clock and adjusted clock just changed by this much, in milliseconds (approximately)
    • restart

      public void restart()
      A "soft" restart, primarily of the comm system, after a port change or large step-change in system time. Does not stop the whole JVM, so it is safe even in the absence of the wrapper. This is not a graceful restart - all peer connections are dropped immediately.

      As of 0.8.8, this returns immediately and does the actual restart in a separate thread. Poll isAlive() if you need to know when the restart is complete.

      Not recommended for external use.

    • main

      public static void main(String[] args)
      Usage: Router [rebuild] No other options allowed, for now Instantiates Router(), and either installs updates and exits, or calls runRouter().

      Not recommended for embedded use. Applications bundling I2P should instantiate a Router and call runRouter().

      Parameters:
      args - null ok
      Throws:
      IllegalArgumentException - if an unrecognized option is given, or more than one argument is passed
    • getPingFile

      private File getPingFile()
      Returns the file recording when the router last ran.
      Returns:
      the ping file
    • startupLog

      private static void startupLog(String msg)
      Writes a startup line to stderr, before the log system exists. The service wrapper prefixes its own level to every stderr line, so the message carries none.
      Parameters:
      msg - the line to write
    • isOnlyRouterRunning

      private boolean isOnlyRouterRunning()
      Check the file "router.ping", but if that file already exists and was recently written to, return false as there is another instance running.
      Returns:
      true if the router is the only one running
    • beginMarkingLiveliness

      private void beginMarkingLiveliness()
      Start a thread that will periodically update the file "router.ping". isOnlyRouterRunning() MUST have been called previously.
    • getEstimatedDowntime

      public long getEstimatedDowntime()
      How long this router was down before it started, or 0 if unknown.

      This may be used for a determination of whether to regenerate keys, for example. We use the timestamp of the previous ping file left behind on crash, as set by isOnlyRouterRunning(), if present. Otherwise, the last STOPPED entry in the event log.

      May take a while to run the first time, if it has to go through the event log. Once called, the result is cached.

      Returns:
      the estimated downtime
    • setEstimatedDowntime

      public void setEstimatedDowntime(long downtime)
      Only for soft restart. Not for external use.
      Parameters:
      downtime - the expected downtime in milliseconds, clamped up to a minimum of 1
    • getSharePercentage

      public double getSharePercentage()
      What fraction of the bandwidth specified in our bandwidth limits should we allow to be consumed by participating tunnels?
      Returns:
      a number less than one, not a percentage!
    • get1sRate

      public int get1sRate()
      Max of inbound and outbound rate in bytes per second.
      Returns:
      the 1s rate
    • get1sRate

      public int get1sRate(boolean outboundOnly)
      When outboundOnly is false, outbound rate in bytes per second. When true, max of inbound and outbound rate in bytes per second.
      Parameters:
      outboundOnly - true to report just the outbound rate, false for the larger of the two
      Returns:
      the 1s rate
    • get1sRateIn

      public int get1sRateIn()
      Inbound rate in bytes per second.
      Returns:
      the 1s rate in
    • get15sRate

      public int get15sRate()
      Max of inbound and outbound rate in bytes per second.
      Returns:
      the 15s rate
    • get15sRate

      public int get15sRate(boolean outboundOnly)
      When outboundOnly is false, outbound rate in bytes per second. When true, max of inbound and outbound rate in bytes per second.
      Parameters:
      outboundOnly - true to report just the outbound rate, false for the larger of the two
      Returns:
      the 15s rate
    • get15sRateIn

      public int get15sRateIn()
      Inbound rate in bytes per second.
      Returns:
      the 15s rate in
    • get1mRate

      public int get1mRate()
      Max of inbound and outbound rate in bytes per second.
      Returns:
      the 1m rate
    • get1mRate

      public int get1mRate(boolean outboundOnly)
      When outboundOnly is false, outbound rate in bytes per second. When true, max of inbound and outbound rate in bytes per second.
      Parameters:
      outboundOnly - true to report just the outbound rate, false for the larger of the two
      Returns:
      the 1m rate
    • get1mRateIn

      public int get1mRateIn()
      Inbound rate in bytes per second.
      Returns:
      the 1m rate in