- All Implemented Interfaces:
I2PSocketManager.DisconnectListener
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 Summary
FieldsModifier and TypeFieldDescriptionstatic final booleanDefault for the collapsible page panels: start them collapsed.static final booleanDefault for the add-torrent and create-torrent forms: show them only on page one.static final booleanDefault for the image lightbox viewer: load it.static final booleanDefault for the torrents-page status filter: hide it.static final booleanDefault for the DHT: participate in it.static final booleanDefault for open trackers: announce to them as backups.static final booleanDefault for inbound tunnels: a fixed hop count.static final booleanDefault for outbound tunnels: a fixed hop count.static final StringUser agent for eepget requests.static final intCeiling on the peers one torrent will hold at once.static final StringClient 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.static final StringOptional comma-separated subset of client names to choose from whenPROP_CLIENT_IDis "random"; unknown names are ignored.static final StringBandwidth throttle property.Constructor Summary
ConstructorsConstructorDescriptionCreate a utility instance bound to the given context, with the default base name and no disconnect listener.I2PSnarkUtil(I2PAppContext ctx, String baseName, I2PSocketManager.DisconnectListener discon) Create a utility instance bound to the given context.Method Summary
Modifier and TypeMethodDescriptionvoidBan the given destination hash for the given period.booleanWhether the page panels start collapsed.booleanWhether peer comments are fetched and shown.booleanconnect()Connect to the router, if we aren't already.(package private) I2PSocketConnect to the given peer over the shared destination.(package private) I2PSocketConnect 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.booleanWhether the shared I2CP session is up.voidTear down the shared session and every per-torrent destination.booleanWhether the add-torrent and create-torrent forms show past page one.booleanWhether the image lightbox viewer is loaded.booleanWhether the hop count of inbound torrent tunnels is randomized.booleanWhether the hop count of outbound torrent tunnels is randomized.Fetch the given URL, returning the file it is stored in, or null on error.Fetch the given URL to a file.Fetch the given URL to a file.Fetch the given URL through the torrent's own destination, which must already exist or nothing is fetched.byte[]Fetch to memory.byte[]Fetch to memory through the torrent's own destination.Fetch the given URL to a file.The API key, or null if not set.The API target base path.List of open tracker announce URLs to use as backups even if disabled.longDuration of the ban applied to peers with an excessive discard ratio.getClientID(byte[] ih) The spoofed client identity for the torrent's destination, or null when identifying as I2PSnark.The comments file name.The context this utility is bound to.(package private) DestinationgetDestination(String ip) Base64 Hash or Hash.i2p or name.i2p using naming service.(package private) static DestinationResolves a base64-encoded destination string.getDHT()The main DHT instance, or null if disabled or not started.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.The EepProxy host configured.intThe EepProxy port configured.booleanWhether an EepProxy is configured.booleanWhether files in the data directory are world-readable.The I2CP host configured.A copy of the I2CP options.intThe I2CP port configured.intThe maximum number of connections per torrent.intThe maximum number of per-torrent destinations in multi-dest mode, 0 for one destination per torrent.intMaximum number of files a torrent may contain.intThe maximum upload bandwidth per torrent.intThe maximum number of uploaders per torrent.booleanWhether each torrent runs on its own destination.(package private) DestinationThe shared destination.(package private) DestinationgetMyDestination(byte[] ih) The destination for the torrent, or the shared destination when multi-dest is disabled or the torrent has no destination.(package private) static StringgetNickname(String name) The tunnel nickname for a torrent's destination, "I2PSnark - <name>" with the name reduced to just the content title, truncated toMAX_NAME_LENGTHcharacters plus an ellipsis.List of open tracker announce URLs to use as backups.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.Full Base64 of the Destination.getOurIPString(byte[] ih) Full Base64 of the destination for the torrent.intThe number of shared pool slots, so a caller can bucket torrents by pool without recomputinggetPoolIndex(byte[])per torrent per peer.intgetPoolIndex(byte[] ih) Pool index that would be assigned to the torrent, -1 when pooling is off.(package private) static StringgetPoolNickname(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.booleanWhether new torrents preallocate their storage files.booleanWhether to preserve original torrent file names (true) or remap to a safe charset (false, default).The shared server socket.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.booleanWhether BEP 47 padding files are added to new torrents created by I2PSnark, so each file except the last ends on a piece boundary.For FetchAndAdd.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.longWhen did we connect to the network? For RPC.intThe maximum startup delay in minutes.intThe minimum startup delay in minutes.A translated plural string for the given count.A translated string for the given key.Translate a string with a parameter This is a lot more expensive than getString(s, ctx), so use sparingly.Translate a string with two parameters.The temporary directory used for downloads in progress.The staging directory configured viai2psnark.tempDirin i2psnark.config, or null if the staging feature is disabled.All active transient destinations, for the tunnel quantity ramp in the IdleChecker.int[]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.The shared UDP tracker client, or null if disabled or not started.getUDPTrackerClient(byte[] ih) The UDP tracker client for the torrent's destination, or the shared client when the torrent has no destination.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.booleanWhether hops are randomly varied for inbound torrent tunnels.booleanWhether hops are randomly varied for outbound torrent tunnels.booleanWhether both an API target and key are configured.booleanWhether to disconnect peers that cancel most of what they request.booleanIs the given destination hash banned?booleanWhether an I2CP connection attempt is in progress.booleanisKnownOpenTracker(String url) Is this announce URL probably for an open tracker?booleanWhether a metadata lookup requested by a tracker such as zzzot is outstanding.(package private) static voidloadProps(Properties props, File f) Load a properties file written bystoreProps(Properties, File): UTF-8, "key=value" per line.Look up a destination by name.static intParse an int, returning the default on null or parse failure.static longParse a long, returning the default on null or parse failure.booleanWhether peer ratings are collected and shown.voidDestroy all transient destinations.voidremoveTorrentDest(String key) Remove and destroy the destination for a torrent, destroying a pooled destination only when its last torrent is removed.(package private) StringrewriteAnnounce(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.voidHandle the I2CP session being disconnected, dropping the manager reference.voidConfigure the API target and key.voidsetBanDiscardPeriod(long period) Set the duration of the ban applied to peers with an excessive discard ratio.voidsetBanDiscardRatio(boolean ban) Whether to disconnect peers that cancel most of what they request.voidsetClientId(String setting) Client identity spoofing.voidsetClientIdCandidates(List<ClientID.Profile> candidates) Restrict the candidate set for random client selection.voidsetCollapsePanels(boolean yes) Whether the page panels start collapsed.voidsetCommentsEnabled(boolean yes) Whether to fetch and show peer comments.voidsetCommentsName(String name) Set the name to post comments and ratings under.voidsetEnableAddCreate(boolean yes) Whether the add-torrent and create-torrent forms show past page one.voidsetEnableLightbox(boolean yes) Whether the image lightbox viewer is loaded.voidsetEnableVaryInboundHops(boolean yes) Whether the hop count of inbound torrent tunnels is randomized.voidsetEnableVaryOutboundHops(boolean yes) Whether the hop count of outbound torrent tunnels is randomized.voidsetFilesPublic(boolean yes) Whether files in the data directory are world-readable.voidsetI2CPConfig(String i2cpHost, int i2cpPort, Map opts) Configure the I2CP connection parameters.voidsetLookupPending(boolean pending) Record whether any tracker lookup is outstanding.voidsetMaxConnections(int limit) Set the maximum number of connections per torrent.voidsetMaxDest(int maxDest) Configure the maximum number of per-torrent destinations, 0-1000; zero is unlimited.voidsetMaxFilesPerTorrent(int max) Maximum number of files a torrent may contain.voidsetMaxUpBW(int limit) This updates ALL the session options (not just the bw) and tells the router.voidsetMaxUploaders(int limit) Set the maximum number of uploaders per torrent.voidsetMultiDest(boolean multiDest) Whether each torrent runs on its own destination.voidsetOpenTrackers(List<String> ot) Configure the open tracker announce URLs to use as backups.voidsetPreallocateFiles(boolean yes) Whether new torrents preallocate their storage files.voidsetPreserveFileNames(boolean yes) Whether to preserve original torrent file names.voidsetRatingsEnabled(boolean yes) Whether to collect and show peer ratings.voidsetShouldPadFiles(boolean yes) Sets whether BEP 47 padding files are added to new torrents.voidsetShowStatusFilter(boolean yes) Whether the torrents-page status filter is shown.voidsetStartupDelayMax(int minutes) Set the maximum startup delay before auto-starting torrents.voidsetStartupDelayMin(int minutes) Set the minimum startup delay before auto-starting torrents.voidsetTempDirProp(String tempDir) Sets the staging directory (or null to disable the feature).voidsetUDPEnabled(boolean yes) Whether to announce to UDP trackers, and to run the UDP tracker client.voidsetUseDHT(boolean yes) Enable or disable the DHT, starting it against the shared session when it is enabled for the first time.voidsetUseOpenTrackers(boolean yes) Whether open trackers are used as backups.voidsetVaryInboundHops(boolean yes) Whether hops are randomly varied for inbound torrent tunnels.voidsetVaryOutboundHops(boolean yes) Whether hops are randomly varied for outbound torrent tunnels.booleanWhether the DHT is used.booleanWhether open trackers are used as backups.booleanWhether the torrents-page status filter is shown.(package private) static voidstoreProps(Properties props, File file) Write the properties to a file, in the formatloadProps(Properties, File)reads: UTF-8, one "key=value" per line, with a two-line header.static StringtoHex(byte[] b) Lower-case hex, two chars per byte, leading zero bytes preserved.static StringReplace known base32 and base64 tracker hosts with their symbolic names, and strip the leading scheme, for display purposes.booleanWhether UDP trackers are used.booleanWhether any peer-supplied data is fetched, that is comments or ratings.
Field Details
DEFAULT_COLLAPSE_PANELS
public static final boolean DEFAULT_COLLAPSE_PANELSDefault for the collapsible page panels: start them collapsed.- See Also:
DEFAULT_SHOW_STATUSFILTER
public static final boolean DEFAULT_SHOW_STATUSFILTERDefault for the torrents-page status filter: hide it.- See Also:
DEFAULT_ENABLE_LIGHTBOX
public static final boolean DEFAULT_ENABLE_LIGHTBOXDefault for the image lightbox viewer: load it.- See Also:
DEFAULT_ENABLE_ADDCREATE
public static final boolean DEFAULT_ENABLE_ADDCREATEDefault 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_OPENTRACKERSDefault for open trackers: announce to them as backups.- See Also:
DEFAULT_VARY_INBOUND_HOPS
public static final boolean DEFAULT_VARY_INBOUND_HOPSDefault for inbound tunnels: a fixed hop count.- See Also:
DEFAULT_VARY_OUTBOUND_HOPS
public static final boolean DEFAULT_VARY_OUTBOUND_HOPSDefault for outbound tunnels: a fixed hop count.- See Also:
MAX_CONNECTIONS
public static final int MAX_CONNECTIONSCeiling on the peers one torrent will hold at once.- See Also:
PROP_MAX_BW
DEFAULT_USE_DHT
public static final boolean DEFAULT_USE_DHTDefault for the DHT: participate in it.- See Also:
EEPGET_USER_AGENT
User agent for eepget requests.- See Also:
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
Optional comma-separated subset of client names to choose from whenPROP_CLIENT_IDis "random"; unknown names are ignored.- See Also:
Constructor Details
I2PSnarkUtil
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
Create a utility instance bound to the given context.- Parameters:
ctx- the I2P context to take logging, randomness and the temp directory frombaseName- generally "i2psnark"discon- notified when the I2CP session drops, or null for no callback
Method Details
getContext
The context this utility is bound to.- Returns:
- the I2PAppContext this utility was constructed with
setI2CPConfig
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
Is the given destination hash banned?- Parameters:
h- destination hash being tested- Returns:
- true if banned
banPeer
Ban the given destination hash for the given period. Does not remove any existing ban of the same hash.- Parameters:
h- destination hash to banperiod- 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
getI2CPPort
public int getI2CPPort()The I2CP port configured.- Returns:
- the i2 c p port
getI2CPOptions
getEepProxyHost
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
The staging directory configured viai2psnark.tempDirin 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
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
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
getAPIKey
setAPI
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
SnarkManageras lookups are submitted and cleared as they resolve or are swept. Consulted byIdleCheckerto 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 recomputinggetPoolIndex(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
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 byClientID.getByName(String).- Parameters:
setting- the i2psnark.clientId value
setClientIdCandidates
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
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
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
The tunnel nickname for a torrent's destination, "I2PSnark - <name>" with the name reduced to just the content title, truncated toMAX_NAME_LENGTHcharacters 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
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 hashname- torrent name, used in the tunnel nickname- Returns:
- the destination, or null if the session could not be created
getPoolNickname
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 ingetOrCreateTorrentDest(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
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
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
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
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
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
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
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
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:
sessionDisconnectedin interfaceI2PSocketManager.DisconnectListener
getDHT
The main DHT instance, or null if disabled or not started.- Returns:
- null if disabled or not started
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
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
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
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 banlistedih- 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
get
get
get
Fetch the given URL through the torrent's own destination, which must already exist or nothing is fetched.- Parameters:
url- the URL to fetchrewrite- if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announceretries- if > 0, set timeout to a few secondsih- the torrent's info hash- Returns:
- the file it is stored in, or null on error
get
Fetch the given URL to a file.- Parameters:
url- the URL to fetchrewrite- if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announceretries- if > 0, set timeout to a few seconds- Returns:
- the file it is stored in, or null on error
get
Fetch to memory.- Parameters:
url- the URL to fetchrewrite- if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announceretries- if < 0, set timeout to a few secondsinitialSize- initial capacity of the output buffer, in bytesmaxSize- 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 fetchrewrite- if true, convert http://KEY.i2p/foo/announce to http://i2p/KEY/foo/announceretries- if < 0, set timeout to a few secondsinitialSize- initial capacity of the output buffer, in bytesmaxSize- fails if greaterih- the torrent's info hashWhen 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
getOurIPString
getMyDestination
getDestinationFromBase64
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
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
rewriteAnnounce
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
setOpenTrackers
getOpenTrackers
isKnownOpenTracker
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
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
Set the name to post comments and ratings under.- Parameters:
name- the author name shown on our own comments and ratings
getCommentsName
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
Lower-case hex, two chars per byte, leading zero bytes preserved.Delegates to
DataHelper.toString(byte[]), which is the canonical formatter and differs fromDataHelper.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 always2 * b.length.- Parameters:
b- non-null bytes to render- Returns:
- hex string of length 2 * b.length
parseInt
Parse an int, returning the default on null or parse failure.- Parameters:
s- may be nulldflt- returned on failure- Returns:
- the parsed value, or dflt if s is null or not an int
parseLong
Parse a long, returning the default on null or parse failure.- Parameters:
s- may be nulldflt- returned on failure- Returns:
- the parsed value, or dflt if s is null or not a long
getString
getString
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
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 translatedo2- second parameter, not translated- Returns:
- the translated string, with {0} and {1} replaced by o and o2
getString
loadProps
Load a properties file written bystoreProps(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 fillf- the file to read- Throws:
IOException- on read failure
storeProps
Write the properties to a file, in the formatloadProps(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 writefile- the file to write to- Throws:
IOException- on write or rename failure, or if an entry had to be skipped