java.lang.Object
org.klomp.snark.I2PSnarkUtil
All Implemented Interfaces:
I2PSocketManager.DisconnectListener

public class I2PSnarkUtilextends Object implements I2PSocketManager.DisconnectListener
I2P-specific utilities and context management for I2PSnark.

This class provides I2P network integration and serves as a context object for I2PSnark operations. It handles:

  • I2P socket management and connection configuration
  • Proxy settings for external tracker communication
  • Peer banlist management
  • Bandwidth and connection limits
  • DHT integration and UDP tracker support
  • File and directory management
  • UI preferences and display options
  • Comments and ratings system configuration

This class acts as a singleton-like context that allows multiple individual Snark instances to run while sharing common I2P configuration and resources. Note that while multiple Snarks can share one I2PSnarkUtil instance, multiple SnarkManagers are not supported due to static resources.

  • Field Details

    • DEFAULT_COLLAPSE_PANELS

      public static final boolean DEFAULT_COLLAPSE_PANELS
      Default for the collapsible page panels: start them collapsed.
      See Also:
    • DEFAULT_SHOW_STATUSFILTER

      public static final boolean DEFAULT_SHOW_STATUSFILTER
      Default for the torrents-page status filter: hide it.
      See Also:
    • DEFAULT_ENABLE_LIGHTBOX

      public static final boolean DEFAULT_ENABLE_LIGHTBOX
      Default for the image lightbox viewer: load it.
      See Also:
    • DEFAULT_ENABLE_ADDCREATE

      public static final boolean DEFAULT_ENABLE_ADDCREATE
      Default for the add-torrent and create-torrent forms: show them only on page one.
      See Also:
    • DEFAULT_USE_OPENTRACKERS

      public static final boolean DEFAULT_USE_OPENTRACKERS
      Default for open trackers: announce to them as backups.
      See Also:
    • DEFAULT_VARY_INBOUND_HOPS

      public static final boolean DEFAULT_VARY_INBOUND_HOPS
      Default for inbound tunnels: a fixed hop count.
      See Also:
    • DEFAULT_VARY_OUTBOUND_HOPS

      public static final boolean DEFAULT_VARY_OUTBOUND_HOPS
      Default for outbound tunnels: a fixed hop count.
      See Also:
    • MAX_CONNECTIONS

      public static final int MAX_CONNECTIONS
      Ceiling on the peers one torrent will hold at once.
      See Also:
    • PROP_MAX_BW

      public static final String PROP_MAX_BW
      Bandwidth throttle property.
      See Also:
    • DEFAULT_USE_DHT

      public static final boolean DEFAULT_USE_DHT
      Default for the DHT: participate in it.
      See Also:
    • EEPGET_USER_AGENT

      public static final String EEPGET_USER_AGENT
      User agent for eepget requests.
      See Also:
    • PROP_CLIENT_ID

      public static final String PROP_CLIENT_ID
      Client identity spoofing setting: empty (default, identify as I2PSnark), "random" to pick a random known client profile per destination per run, or the name of a known client to always impersonate it.
      See Also:
    • PROP_CLIENT_IDS

      public static final String PROP_CLIENT_IDS
      Optional comma-separated subset of client names to choose from when PROP_CLIENT_ID is "random"; unknown names are ignored.
      See Also:
  • Constructor Details

    • I2PSnarkUtil

      public I2PSnarkUtil(I2PAppContext ctx)
      Create a utility instance bound to the given context, with the default base name and no disconnect listener.
      Parameters:
      ctx - the I2P context to take logging, randomness and the temp directory from
    • I2PSnarkUtil

      public I2PSnarkUtil(I2PAppContext ctx, String baseName, I2PSocketManager.DisconnectListener discon)
      Create a utility instance bound to the given context.
      Parameters:
      ctx - the I2P context to take logging, randomness and the temp directory from
      baseName - generally "i2psnark"
      discon - notified when the I2CP session drops, or null for no callback
  • Method Details

    • getContext

      public I2PAppContext getContext()
      The context this utility is bound to.
      Returns:
      the I2PAppContext this utility was constructed with
    • setI2CPConfig

      public void setI2CPConfig(String i2cpHost, int i2cpPort, Map opts)
      Configure the I2CP connection parameters.
      Parameters:
      i2cpHost - may be null for no change
      i2cpPort - may be 0 for no change
      opts - may be null for no change
    • setMaxUploaders

      public void setMaxUploaders(int limit)
      Set the maximum number of uploaders per torrent.
      Parameters:
      limit - the maximum number of uploaders
    • setMaxUpBW

      public void setMaxUpBW(int limit)
      This updates ALL the session options (not just the bw) and tells the router.
      Parameters:
      limit - maximum upload bandwidth per torrent in KB/s
    • setMaxConnections

      public void setMaxConnections(int limit)
      Set the maximum number of connections per torrent.
      Parameters:
      limit - the maximum number of connections
    • isBanDiscardRatio

      public boolean isBanDiscardRatio()
      Whether to disconnect peers that cancel most of what they request.
      Returns:
      true if the discard-ratio auto-ban is enabled
    • setBanDiscardRatio

      public void setBanDiscardRatio(boolean ban)
      Whether to disconnect peers that cancel most of what they request.
      Parameters:
      ban - true to enable the discard-ratio auto-ban
    • getBanDiscardPeriod

      public long getBanDiscardPeriod()
      Duration of the ban applied to peers with an excessive discard ratio.
      Returns:
      the ban period in milliseconds
    • setBanDiscardPeriod

      public void setBanDiscardPeriod(long period)
      Set the duration of the ban applied to peers with an excessive discard ratio.
      Parameters:
      period - the ban period in milliseconds
    • isBanned

      public boolean isBanned(Hash h)
      Is the given destination hash banned?
      Parameters:
      h - destination hash being tested
      Returns:
      true if banned
    • banPeer

      public void banPeer(Hash h, long period)
      Ban the given destination hash for the given period. Does not remove any existing ban of the same hash.
      Parameters:
      h - destination hash to ban
      period - the ban period in milliseconds
    • setStartupDelayMin

      public void setStartupDelayMin(int minutes)
      Set the minimum startup delay before auto-starting torrents.
      Parameters:
      minutes - the minimum startup delay in minutes
    • setStartupDelayMax

      public void setStartupDelayMax(int minutes)
      Set the maximum startup delay before auto-starting torrents.
      Parameters:
      minutes - the maximum startup delay in minutes
    • getI2CPHost

      public String getI2CPHost()
      The I2CP host configured.
      Returns:
      the i2 c p host
    • getI2CPPort

      public int getI2CPPort()
      The I2CP port configured.
      Returns:
      the i2 c p port
    • getI2CPOptions

      public Map<String,String> getI2CPOptions()
      A copy of the I2CP options.
      Returns:
      a copy of the live option map, safe to modify
    • getEepProxyHost

      public String getEepProxyHost()
      The EepProxy host configured.
      Returns:
      the eep proxy host
    • getEepProxyPort

      public int getEepProxyPort()
      The EepProxy port configured.
      Returns:
      the eep proxy port
    • getEepProxySet

      public boolean getEepProxySet()
      Whether an EepProxy is configured.
      Returns:
      the eep proxy set
    • getMaxUploaders

      public int getMaxUploaders()
      The maximum number of uploaders per torrent.
      Returns:
      the max uploaders
    • getMaxUpBW

      public int getMaxUpBW()
      The maximum upload bandwidth per torrent.
      Returns:
      maximum upload bandwidth per torrent in KB/s
    • getMaxConnections

      public int getMaxConnections()
      The maximum number of connections per torrent.
      Returns:
      the max connections
    • getStartupDelayMin

      public int getStartupDelayMin()
      The minimum startup delay in minutes.
      Returns:
      the minimum startup delay
    • getStartupDelayMax

      public int getStartupDelayMax()
      The maximum startup delay in minutes.
      Returns:
      the maximum startup delay
    • getFilesPublic

      public boolean getFilesPublic()
      Whether files in the data directory are world-readable.
      Returns:
      the files public
    • setFilesPublic

      public void setFilesPublic(boolean yes)
      Whether files in the data directory are world-readable.
      Parameters:
      yes - true to make data directory files world-readable
    • getPreallocateFiles

      public boolean getPreallocateFiles()
      Whether new torrents preallocate their storage files.
      Returns:
      the preallocate files
    • setPreallocateFiles

      public void setPreallocateFiles(boolean yes)
      Whether new torrents preallocate their storage files.
      Parameters:
      yes - true to preallocate storage for new torrents
    • getPreserveFileNames

      public boolean getPreserveFileNames()
      Whether to preserve original torrent file names (true) or remap to a safe charset (false, default).
      Returns:
      true if original file names are preserved
    • setPreserveFileNames

      public void setPreserveFileNames(boolean yes)
      Whether to preserve original torrent file names.
      Parameters:
      yes - true to keep the torrent's own file names, false to remap to a safe charset
    • getShouldPadFiles

      public boolean getShouldPadFiles()
      Whether BEP 47 padding files are added to new torrents created by I2PSnark, so each file except the last ends on a piece boundary. Set by SnarkManager when the config is loaded or re-read; consumed by Storage when creating torrents.
      Returns:
      whether new torrents are padded
    • setShouldPadFiles

      public void setShouldPadFiles(boolean yes)
      Sets whether BEP 47 padding files are added to new torrents.
      Parameters:
      yes - true to pad new torrents so each file ends on a piece boundary
    • getTempDirProp

      public String getTempDirProp()
      The staging directory configured via i2psnark.tempDir in i2psnark.config, or null if the staging feature is disabled. Set by SnarkManager at startup and from the I2PSnark configuration page; consumed by Storage.
      Returns:
      the staging directory, or null
    • setTempDirProp

      public void setTempDirProp(String tempDir)
      Sets the staging directory (or null to disable the feature). The value should already be trimmed and unquoted.
      Parameters:
      tempDir - staging directory, already trimmed and unquoted, or null to disable
    • getTempDir

      public File getTempDir()
      The temporary directory used for downloads in progress.
      Returns:
      the temp dir
    • getMaxFilesPerTorrent

      public int getMaxFilesPerTorrent()
      Maximum number of files a torrent may contain.
      Returns:
      the max files per torrent
    • setMaxFilesPerTorrent

      public void setMaxFilesPerTorrent(int max)
      Maximum number of files a torrent may contain.
      Parameters:
      max - the maximum number of files, raised to 1 if less
    • getAPITarget

      public String getAPITarget()
      The API target base path.
      Returns:
      the a p i target
    • getAPIKey

      public String getAPIKey()
      The API key, or null if not set.
      Returns:
      the a p i key
    • setAPI

      public void setAPI(String target, String key)
      Configure the API target and key.
      Parameters:
      target - the API target base path
      key - the API key
    • hasAPIKey

      public boolean hasAPIKey()
      Whether both an API target and key are configured.
      Returns:
      whether a p i key is present
    • getVaryInboundHops

      public boolean getVaryInboundHops()
      Whether hops are randomly varied for inbound torrent tunnels.
      Returns:
      the vary inbound hops
    • getVaryOutboundHops

      public boolean getVaryOutboundHops()
      Whether hops are randomly varied for outbound torrent tunnels.
      Returns:
      the vary outbound hops
    • setVaryInboundHops

      public void setVaryInboundHops(boolean yes)
      Whether hops are randomly varied for inbound torrent tunnels.
      Parameters:
      yes - true to randomize the hop count of inbound torrent tunnels
    • setVaryOutboundHops

      public void setVaryOutboundHops(boolean yes)
      Whether hops are randomly varied for outbound torrent tunnels.
      Parameters:
      yes - true to randomize the hop count of outbound torrent tunnels
    • connect

      public boolean connect()
      Connect to the router, if we aren't already.
      Returns:
      true if connected
    • getMultiDest

      public boolean getMultiDest()
      Whether each torrent runs on its own destination.
      Returns:
      whether each torrent runs on its own destination
    • isLookupPending

      public boolean isLookupPending()
      Whether a metadata lookup requested by a tracker such as zzzot is outstanding.

      Set by SnarkManager as lookups are submitted and cleared as they resolve or are swept. Consulted by IdleChecker to hold the tunnel floor: trackers use these lookups to resolve infohashes to torrent names, and they are answered over the same session the torrents use, so the tunnels have to stay up for as long as one is outstanding. Without it a lookup's arrival and expiry could time a reduction into a pool that a torrent is about to need.

      Returns:
      whether a lookup is outstanding
    • setLookupPending

      public void setLookupPending(boolean pending)
      Record whether any tracker lookup is outstanding.
      Parameters:
      pending - true while at least one lookup is in flight
    • getPoolCount

      public int getPoolCount()
      The number of shared pool slots, so a caller can bucket torrents by pool without recomputing getPoolIndex(byte[]) per torrent per peer.
      Returns:
      the configured pool count, 0 when pooling is off
    • setMultiDest

      public void setMultiDest(boolean multiDest)
      Whether each torrent runs on its own destination. Also reapplies the DHT serving mode, which in multi-dest mode answers no tracker queries.
      Parameters:
      multiDest - true to give each torrent a destination of its own
    • getMaxDest

      public int getMaxDest()
      The maximum number of per-torrent destinations in multi-dest mode, 0 for one destination per torrent.
      Returns:
      the maximum number of per-torrent destinations
    • setMaxDest

      public void setMaxDest(int maxDest)
      Configure the maximum number of per-torrent destinations, 0-1000; zero is unlimited.
      Parameters:
      maxDest - the maximum number of destinations, 0-1000; zero is unlimited
    • setClientId

      public void setClientId(String setting)
      Client identity spoofing. Empty (default): random known client profiles per pool in multi-dest mode, classic I2PSnark identity otherwise. "random": random profiles in all modes. "i2psnark": classic identity even in multi-dest mode. Any other value: the name of a known client to always impersonate, as accepted by ClientID.getByName(String).
      Parameters:
      setting - the i2psnark.clientId value
    • setClientIdCandidates

      public void setClientIdCandidates(List<ClientID.Profile> candidates)
      Restrict the candidate set for random client selection. Unknown names are dropped; an empty list selects from all known clients.
      Parameters:
      candidates - the parsed candidate list, may be empty
    • getClientID

      public ClientID.Profile getClientID(byte[] ih)
      The spoofed client identity for the torrent's destination, or null when identifying as I2PSnark. All torrents sharing a destination share one identity: a single profile per run when multi-dest is off, one profile per pool index otherwise, and one profile per torrent for dedicated destinations. With no i2psnark.clientId configured, multi-dest pools get random profiles by default and single-dest mode keeps the classic I2PSnark identity.
      Parameters:
      ih - the torrent's info hash, or null
      Returns:
      the profile, or null for no spoofing
    • getUserAgent

      public String getUserAgent(byte[] ih)
      The HTTP User-Agent to send for the torrent's requests: the spoofed profile's UA when spoofing is on, else the default I2PSnark UA.
      Parameters:
      ih - the torrent's info hash, or null
      Returns:
      the User-Agent string, never null
    • getNickname

      static String getNickname(String name)
      The tunnel nickname for a torrent's destination, "I2PSnark - <name>" with the name reduced to just the content title, truncated to MAX_NAME_LENGTH characters plus an ellipsis. Parentheses and brackets with anything inside them (year, resolution, release group), a metadata tail after the first dash, file extensions and common quality tokens (resolution, codec, source) are removed, so the nickname is shorter and the title stands out on the console's tunnels page. Local only; not shared with trackers or the DHT.
      Parameters:
      name - the torrent name
      Returns:
      the derived nickname, never null
    • getOrCreateTorrentDest

      public TorrentDest getOrCreateTorrentDest(String key, String name)
      The destination for a torrent, creating the destination and session on first use, or assigning the torrent to a shared pool when the configured maximum number of destinations is exceeded. Only used when multi-dest is enabled.
      Parameters:
      key - Base64 encoding of the torrent's info hash
      name - torrent name, used in the tunnel nickname
      Returns:
      the destination, or null if the session could not be created
    • getPoolNickname

      static String getPoolNickname(int poolNum)
      Tunnel nickname for a shared pool, "I2PSnark - Pool <n>", with the pool's member names carried in the i2psnark.poolMembers session property for the pool tooltip. Single-torrent pools keep their torrent's nickname instead. This is applied by TorrentDest only when a second torrent joins the pool.
      Parameters:
      poolNum - the sequential pool number, assigned when the pool destination was created
      Returns:
      the pool nickname, never null
    • getPoolIndex

      public int getPoolIndex(byte[] ih)
      Pool index that would be assigned to the torrent, -1 when pooling is off. Deterministic within a run, so batch starts can compute pool membership up front; matches the assignment in getOrCreateTorrentDest(String, String).
      Parameters:
      ih - the torrent's info hash, or null
      Returns:
      the pool index in [0, _maxDest), or -1 for a dedicated destination
    • removeTorrentDest

      public void removeTorrentDest(String key)
      Remove and destroy the destination for a torrent, destroying a pooled destination only when its last torrent is removed.
      Parameters:
      key - Base64 encoding of the torrent's info hash
    • getTorrentDests

      public Collection<TorrentDest> getTorrentDests()
      All active transient destinations, for the tunnel quantity ramp in the IdleChecker.
      Returns:
      all active transient destinations, never null
    • getTunnelCounts

      public int[] getTunnelCounts()
      The inbound and outbound tunnel counts allocated to our sessions, summed over the primary session and all per-torrent destinations, so both grow with the number of sessions in multi-dest mode. Inbound tunnels are counted exactly as the number of leases in each session's current lease set, one lease per allocated inbound tunnel. Outbound tunnels are not visible to an I2CP client, so the count is the effective outbound.quantity configured for each session, which this application assigns dynamically (build options and the IdleChecker ramp) and the router maintains as the session's outbound pool. Counts are zero before the sessions are connected.
      Returns:
      int[] of {inbound, outbound}, never null
    • removeAllTorrentDests

      public void removeAllTorrentDests()
      Destroy all transient destinations. Called on shutdown.
    • getSocketManager

      public I2PSocketManager getSocketManager(byte[] ih)
      The socket manager for the torrent's destination, or the shared manager when multi-dest is disabled or the torrent has no destination.
      Parameters:
      ih - the torrent's info hash
      Returns:
      the socket manager
    • getServerSocket

      public I2PServerSocket getServerSocket(byte[] ih)
      The server socket for the torrent's destination, or the shared server socket when multi-dest is disabled or the torrent has no destination.
      Parameters:
      ih - the torrent's info hash
      Returns:
      the server socket
    • getMyDestination

      Destination getMyDestination(byte[] ih)
      The destination for the torrent, or the shared destination when multi-dest is disabled or the torrent has no destination.
      Parameters:
      ih - the torrent's info hash
      Returns:
      the torrent's own destination, or the shared one
    • getOurIPString

      public String getOurIPString(byte[] ih)
      Full Base64 of the destination for the torrent.
      Parameters:
      ih - the torrent's info hash, or null for the shared destination
      Returns:
      the destination string, or the shared destination string
    • getDHTForTorrent

      public DHT getDHTForTorrent(byte[] ih)
      The DHT instance for the torrent, on the torrent's own destination, or the shared DHT instance when multi-dest is disabled or the DHT is disabled.
      Parameters:
      ih - the torrent's info hash
      Returns:
      the DHT instance
    • getUDPTrackerClient

      public UDPTrackerClient getUDPTrackerClient(byte[] ih)
      The UDP tracker client for the torrent's destination, or the shared client when the torrent has no destination.
      Parameters:
      ih - the torrent's info hash
      Returns:
      the UDP tracker client
    • sessionDisconnected

      public void sessionDisconnected()
      Handle the I2CP session being disconnected, dropping the manager reference.
      Specified by:
      sessionDisconnected in interface I2PSocketManager.DisconnectListener
    • getDHT

      public DHT getDHT()
      The main DHT instance, or null if disabled or not started.
      Returns:
      null if disabled or not started
    • getUDPTrackerClient

      public UDPTrackerClient getUDPTrackerClient()
      The shared UDP tracker client, or null if disabled or not started.
      Returns:
      null if disabled or not started
    • connected

      public boolean connected()
      Whether the shared I2CP session is up.
      Returns:
      true if a session manager has been created for the shared session
    • isConnecting

      public boolean isConnecting()
      Whether an I2CP connection attempt is in progress.
      Returns:
      true if no manager exists yet but a connection attempt is underway
    • getSocketManager

      public I2PSocketManager getSocketManager()
      For FetchAndAdd.
      Returns:
      null if not connected
    • disconnect

      public void disconnect()
      Tear down the shared session and every per-torrent destination.

      The manager is taken into a local and the field cleared before it is destroyed, so that a reader which gets there after this point sees no manager at all rather than one that is being torn down. Readers that were already using a manager keep their local reference and must tolerate the I2CP connection going away under them.

    • getStartedTime

      public long getStartedTime()
      When did we connect to the network? For RPC.
      Returns:
      0 if not connected
    • connect

      I2PSocket connect(PeerID peer) throws IOException
      Connect to the given peer over the shared destination.
      Parameters:
      peer - the peer to dial, whose destination must not be ours or banlisted
      Returns:
      the connected socket, or null if the connection could not be established
      Throws:
      IOException - if the socket manager is missing, or the peer is us, banlisted, or unreachable
    • connect

      I2PSocket connect(PeerID peer, byte[] ih) throws IOException
      Connect to the given destination through the torrent's own destination, or the shared destination if multi-dest is disabled or the torrent has no destination yet.
      Parameters:
      peer - the peer to dial, whose destination must not be ours or banlisted
      ih - the torrent's info hash
      Returns:
      the connected socket, or null if the connection could not be established
      Throws:
      IOException - if the socket manager is missing, or the peer is us, banlisted, or unreachable
    • get

      public File get(String url)
      Fetch the given URL, returning the file it is stored in, or null on error. No retries.
      Parameters:
      url - the URL to fetch
      Returns:
      the file it is stored in, or null on error
    • get

      public File get(String url, boolean rewrite)
      Fetch the given URL to a file.
      Parameters:
      url - the URL to fetch
      rewrite - if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announce
      Returns:
      the file it is stored in, or null on error
    • get

      public File get(String url, int retries)
      Fetch the given URL to a file.
      Parameters:
      url - the URL to fetch
      retries - if > 0, set timeout to a few seconds
      Returns:
      the file it is stored in, or null on error
    • get

      public File get(String url, boolean rewrite, int retries, byte[] ih)
      Fetch the given URL through the torrent's own destination, which must already exist or nothing is fetched.
      Parameters:
      url - the URL to fetch
      rewrite - if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announce
      retries - if > 0, set timeout to a few seconds
      ih - the torrent's info hash
      Returns:
      the file it is stored in, or null on error
    • get

      public File get(String url, boolean rewrite, int retries)
      Fetch the given URL to a file.
      Parameters:
      url - the URL to fetch
      rewrite - if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announce
      retries - if > 0, set timeout to a few seconds
      Returns:
      the file it is stored in, or null on error
    • get

      public byte[] get(String url, boolean rewrite, int retries, int initialSize, int maxSize)
      Fetch to memory.
      Parameters:
      url - the URL to fetch
      rewrite - if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announce
      retries - if < 0, set timeout to a few seconds
      initialSize - initial capacity of the output buffer, in bytes
      maxSize - fails if greater
      Returns:
      null on error
    • get

      public byte[] get(String url, boolean rewrite, int retries, int initialSize, int maxSize, byte[] ih)
      Fetch to memory through the torrent's own destination.
      Parameters:
      url - the URL to fetch
      rewrite - if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announce
      retries - if < 0, set timeout to a few seconds
      initialSize - initial capacity of the output buffer, in bytes
      maxSize - fails if greater
      ih - the torrent's info hash

      When the torrent has no destination of its own - which is every torrent while getMultiDest() is off, the default - the fetch goes over the shared session instead. Returning null here is what silently disabled every HTTP tracker announce: all of the default open trackers are http, and each one failed immediately with "No response from", leaving a magnet with no working peer source at all. Fetching over the shared session is exactly what the single-destination configuration already means.

      Returns:
      null on error
    • getServerSocket

      public I2PServerSocket getServerSocket()
      The shared server socket.
      Returns:
      the server socket
    • getOurIPString

      public String getOurIPString()
      Full Base64 of the Destination.
      Returns:
      the our IP string
    • getMyDestination

      Destination getMyDestination()
      The shared destination.
      Returns:
      dest or null
    • getDestinationFromBase64

      static Destination getDestinationFromBase64(String ip)
      Resolves a base64-encoded destination string. Does not use naming service.
      Parameters:
      ip - destination string, with or without .i2p suffix
      Returns:
      the Destination, or null if parsing fails
    • getDestination

      Destination getDestination(String ip)
      Base64 Hash or Hash.i2p or name.i2p using naming service.
      Parameters:
      ip - destination string: base64, a .b32.i2p address, or a name.i2p hostname resolved through the naming service
      Returns:
      the Destination, or null if it cannot be parsed or the name does not resolve
    • lookup

      public String lookup(String name)
      Look up a destination by name. Uses naming service for .i2p names, raw base64 otherwise.
      Parameters:
      name - hostname or base64 destination
      Returns:
      the base64-encoded destination, or null if not found
    • rewriteAnnounce

      String rewriteAnnounce(String origAnnounce)
      Given http://KEY.i2p/foo/announce turn it into http://i2p/KEY/foo/announce Given http://tracker.blah.i2p/foo/announce leave it alone.
      Parameters:
      origAnnounce - the tracker's announce URL, expected to begin with "http://"
      Returns:
      the URL with the key moved into the path, or the input unchanged when the host is too short to be a full destination key
    • trackerB32ToHostname

      public static String trackerB32ToHostname(String url)
      Replace known base32 and base64 tracker hosts with their symbolic names, and strip the leading scheme, for display purposes.
      Parameters:
      url - may be null
      Returns:
      the converted hostname, or null if url is null
    • setOpenTrackers

      public void setOpenTrackers(List<String> ot)
      Configure the open tracker announce URLs to use as backups.
      Parameters:
      ot - non-null list of announce URLs
    • getOpenTrackers

      public List<String> getOpenTrackers()
      List of open tracker announce URLs to use as backups.
      Returns:
      non-null, possibly unmodifiable, empty if disabled
    • isKnownOpenTracker

      public boolean isKnownOpenTracker(String url)
      Is this announce URL probably for an open tracker?
      Parameters:
      url - announce URL, whose host is matched against the known open trackers
      Returns:
      whether known open tracker
    • getBackupTrackers

      public List<String> getBackupTrackers()
      List of open tracker announce URLs to use as backups even if disabled.
      Returns:
      non-null
    • setUseOpenTrackers

      public void setUseOpenTrackers(boolean yes)
      Whether open trackers are used as backups.
      Parameters:
      yes - true to announce to the open trackers as backups
    • shouldUseOpenTrackers

      public boolean shouldUseOpenTrackers()
      Whether open trackers are used as backups.
      Returns:
      whether use open trackers
    • setUseDHT

      public void setUseDHT(boolean yes)
      Enable or disable the DHT, starting it against the shared session when it is enabled for the first time.
      Parameters:
      yes - true to use the DHT
    • shouldUseDHT

      public boolean shouldUseDHT()
      Whether the DHT is used.
      Returns:
      whether use DHT
    • setUDPEnabled

      public void setUDPEnabled(boolean yes)
      Whether to announce to UDP trackers, and to run the UDP tracker client.
      Parameters:
      yes - true to use UDP trackers
    • udpEnabled

      public boolean udpEnabled()
      Whether UDP trackers are used.
      Returns:
      whether udp trackers are enabled
    • setRatingsEnabled

      public void setRatingsEnabled(boolean yes)
      Whether to collect and show peer ratings.
      Parameters:
      yes - true to collect ratings
    • ratingsEnabled

      public boolean ratingsEnabled()
      Whether peer ratings are collected and shown.
      Returns:
      whether ratings are enabled
    • setCommentsEnabled

      public void setCommentsEnabled(boolean yes)
      Whether to fetch and show peer comments.
      Parameters:
      yes - true to fetch comments
    • commentsEnabled

      public boolean commentsEnabled()
      Whether peer comments are fetched and shown.
      Returns:
      whether comments are enabled
    • setCommentsName

      public void setCommentsName(String name)
      Set the name to post comments and ratings under.
      Parameters:
      name - the author name shown on our own comments and ratings
    • getCommentsName

      public String getCommentsName()
      The comments file name.
      Returns:
      non-null, "" if none
    • utCommentsEnabled

      public boolean utCommentsEnabled()
      Whether any peer-supplied data is fetched, that is comments or ratings.
      Returns:
      whether comments or ratings are enabled
    • collapsePanels

      public boolean collapsePanels()
      Whether the page panels start collapsed.
      Returns:
      whether panels start collapsed
    • setCollapsePanels

      public void setCollapsePanels(boolean yes)
      Whether the page panels start collapsed.
      Parameters:
      yes - true to start the panels collapsed
    • showStatusFilter

      public boolean showStatusFilter()
      Whether the torrents-page status filter is shown.
      Returns:
      whether the status filter is shown
    • setShowStatusFilter

      public void setShowStatusFilter(boolean yes)
      Whether the torrents-page status filter is shown.
      Parameters:
      yes - true to show the status filter
    • enableLightbox

      public boolean enableLightbox()
      Whether the image lightbox viewer is loaded.
      Returns:
      whether the lightbox is enabled
    • setEnableLightbox

      public void setEnableLightbox(boolean yes)
      Whether the image lightbox viewer is loaded.
      Parameters:
      yes - true to load the lightbox viewer
    • enableAddCreate

      public boolean enableAddCreate()
      Whether the add-torrent and create-torrent forms show past page one.
      Returns:
      whether the add/create forms are enabled
    • setEnableAddCreate

      public void setEnableAddCreate(boolean yes)
      Whether the add-torrent and create-torrent forms show past page one.
      Parameters:
      yes - true to keep the add/create forms on every page
    • enableVaryInboundHops

      public boolean enableVaryInboundHops()
      Whether the hop count of inbound torrent tunnels is randomized.
      Returns:
      whether inbound hop counts vary
    • enableVaryOutboundHops

      public boolean enableVaryOutboundHops()
      Whether the hop count of outbound torrent tunnels is randomized.
      Returns:
      whether outbound hop counts vary
    • setEnableVaryInboundHops

      public void setEnableVaryInboundHops(boolean yes)
      Whether the hop count of inbound torrent tunnels is randomized.
      Parameters:
      yes - true to randomize the inbound hop count
    • setEnableVaryOutboundHops

      public void setEnableVaryOutboundHops(boolean yes)
      Whether the hop count of outbound torrent tunnels is randomized.
      Parameters:
      yes - true to randomize the outbound hop count
    • toHex

      public static String toHex(byte[] b)
      Lower-case hex, two chars per byte, leading zero bytes preserved.

      Delegates to DataHelper.toString(byte[]), which is the canonical formatter and differs from DataHelper.toHexString(byte[]) in exactly the way info hashes need: it emits the zero bytes that a BigInteger-backed conversion drops, so the output length is always 2 * b.length.

      Parameters:
      b - non-null bytes to render
      Returns:
      hex string of length 2 * b.length
    • parseInt

      public static int parseInt(String s, int dflt)
      Parse an int, returning the default on null or parse failure.
      Parameters:
      s - may be null
      dflt - returned on failure
      Returns:
      the parsed value, or dflt if s is null or not an int
    • parseLong

      public static long parseLong(String s, long dflt)
      Parse a long, returning the default on null or parse failure.
      Parameters:
      s - may be null
      dflt - returned on failure
      Returns:
      the parsed value, or dflt if s is null or not a long
    • getString

      public String getString(String key)
      A translated string for the given key.
      Parameters:
      key - the message bundle key to look up
      Returns:
      the translated string, in the routerconsole.lang property if set, else the current locale
    • getString

      public String getString(String s, Object o)
      Translate a string with a parameter This is a lot more expensive than getString(s, ctx), so use sparingly.
      Parameters:
      s - string to be translated containing {0} The {0} will be replaced by the parameter. Single quotes must be doubled, i.e. ' -> '' in the string.
      o - parameter, not translated. To translate parameter also, use _t("foo {0} bar", _t("baz")) Do not double the single quotes in the parameter. Use autoboxing to call with ints, longs, floats, etc.
      Returns:
      the translated string, with {0} replaced by o
    • getString

      public String getString(String s, Object o, Object o2)
      Translate a string with two parameters. Like the single-parameter form this is a lot more expensive than getString(s, ctx), so use sparingly.
      Parameters:
      s - string to be translated containing {0} and {1} Single quotes must be doubled, i.e. ' -> '' in the string.
      o - first parameter, not translated
      o2 - second parameter, not translated
      Returns:
      the translated string, with {0} and {1} replaced by o and o2
    • getString

      public String getString(int n, String s, String p)
      A translated plural string for the given count.
      Parameters:
      n - the count, selects singular or plural form
      s - the singular form
      p - the plural form
      Returns:
      the translated string
    • loadProps

      static void loadProps(Properties props, File f) throws IOException
      Load a properties file written by storeProps(Properties, File): UTF-8, "key=value" per line. Blank lines, lines starting with '#' or ';', and lines with no '=' are ignored; for the rest, everything after the first '=' is the value.

      Same as DataHelper.loadProps(Properties, File) but allows '#' in values, so we can have filenames with '#' in them in property files. '#' must be in column 1 for a comment.

      Parameters:
      props - the properties to fill
      f - the file to read
      Throws:
      IOException - on read failure
    • storeProps

      static void storeProps(Properties props, File file) throws IOException
      Write the properties to a file, in the format loadProps(Properties, File) reads: UTF-8, one "key=value" per line, with a two-line header. Entries whose key contains one of "#;=\r\n" or whose value contains CR or LF are skipped, and the first such key is reported in the IOException thrown after the rest of the file has been written.

      Writes to a ".tmp" file next to the target and renames it into place, so a reader never sees a half-written file.

      Parameters:
      props - the properties to write
      file - the file to write to
      Throws:
      IOException - on write or rename failure, or if an entry had to be skipped