java.lang.Object
net.i2p.addressbook.HostChecker
Ping tester for address book entries. Tests I2P destinations for reachability and stores results.
Nested Class Summary
Modifier and TypeClassDescriptionprivate classTask to retry category downloads if they initially failed.private static final classSemaphore whose permit limit can change at runtime, so concurrency adjustments apply to a cycle already in progress.static classPing result data structure containing the outcome of a host reachability test.private classTask to ping all destinations in address book.Field Summary
FieldsModifier and TypeFieldDescriptionHosts excluded from checking.private final FileFile listing hosts never to ping.private longModification time of the blacklist file.private final AtomicBooleanWhether the category list has been downloaded.private final AtomicBooleanWhether the last category download succeeded.private final FileFile storing the host categories.private intCategory download attempts so far.private final FileFile holding the checker's settings.private longModification time of the config file.private final I2PAppContextThe app context.private final AtomicBooleanTrue while a ping cycle is running.private static final ThreadLocal<DateFormat> Per-thread date format for the result display.Category assigned to each host.private final FileFile storing the ping results.private final LogLogger for the host checks.private intHosts pinged at once, in effect right now.private final NamingServiceNaming service holding the hosts to check.private longPing cycle interval in effect right now.private final Map<String, HostChecker.PingResult> Latest ping result by host name.private final HostChecker.DynamicSemaphoreLimits how many hosts ping at once.private ScheduledFuture<?> The scheduled ping task, kept for cancellation.private longTimeout for one ping, in effect right now.private final AtomicBooleanTrue while the checker is running.private final ScheduledExecutorServiceExecutor running the ping cycles.private I2PSocketManagerShared socket manager for the pings.private booleanWhether a lease set reply counts as a successful ping.private static final intConnect timeout for the category download.private static final longWait before downloading the category list.private static final intInactivity timeout for the category download.private static final longWait before retrying a failed category download.private static final intTotal timeout for the category download.private static final PatternSplits a category line on commas.private static final intDefault hosts pinged at once.private static final longDefault interval between ping cycles, four hours.private static final longDefault timeout for one ping is 60 seconds.private static final longA host confirmed up within this window stays up when its LeaseSet can't be fetched this cycle.private static final intCap on outbound tunnels for the shared ping session; pings are a bonus check, each tunnel costs a network build.private static final longLimit on one ping cycle before it is cancelled.private static final Comparator<Map.Entry<String, HostChecker.PingResult>> Sorts ping results by timestamp, oldest first.private static final StringConfig key for the concurrent ping limit.private static final StringConfig key for the ping cycle interval.private static final longWait after startup before the first ping cycle.Constructor Summary
ConstructorsConstructorDescriptionConstruct a HostChecker that uses the default naming service This works with the blockfile format (hostsdb.blockfile).HostChecker(NamingService namingService) Construct a HostChecker for given naming service.Method Summary
Modifier and TypeMethodDescriptionprivate static StringLooks up a localized string in the message bundle.private booleanAttempt to download categories file Returns true if successful, false otherwise.private voidRemove hosts from _pingResults that are no longer in the address book This prevents stale entries from accumulating in hosts_check.txt.private HostChecker.PingResultcreatePingResult(boolean reachable, long timestamp, long responseTime, String hostname) Helper method to create PingResult with category.private HostChecker.PingResultcreatePingResult(boolean reachable, long timestamp, long responseTime, String hostname, String leaseSetTypes) Helper method to create PingResult with category and leaseSetTypes.private static PropertiescreatePingSessionOptions(String nickname, int inboundQuantity, int outboundQuantity) Build the I2CP options for a HostChecker ping session.private voidDownload categories file from notbob.i2p Falls back to existing stale categories.txt if download fails.private HostChecker.PingResultfallbackToEepHead(String hostname, long startTime) Fallback method to useEepHeadfor HTTP HEAD request testing Marks site as up if any response is received.private HostChecker.PingResultfallbackToEepHead(String hostname, long startTime, String leaseSetTypes, boolean saveResult) Fallback method to use EepHead for HTTP HEAD request testing Marks site as up if any response is received.private static StringformatLeaseSetTypes(LeaseSet leaseSet) Format LeaseSet encryption types as a string like "[0]" or "[4,0]".Get all host categories.Get all hostnames from the naming service.Get all ping results.getCategory(String hostname) Get category for a hostname.getCategoryDescription(String category) Get description for a category.private DestinationgetDestination(String hostname) Get destination for a hostname from naming service.getPingResult(String hostname) Get ping result for a hostname.booleanGet whether to use LeaseSet checking.private booleanisHostBlacklisted(String hostname) Checks whether a host is excluded from checking.booleanCheck if ping tester is running.booleanWhether a host check cycle is currently in progress.private voidReads the blacklisted hosts from the file.private voidLoad categories from categories.txt file.private voidLoad configuration from addressbook/config.txt file Reads pingInterval and maxConcurrent properties if present.private voidLoad ping results from hosts_check.txt file.private HostChecker.PingResultlookupLeaseSetRemotely(String hostname, Hash destHash, long startTime, long existingResponseTime) Perform remote LeaseSet lookup via floodfill network and record the result.static voidTest method.private voidParse addressbook/config.txt and update the ping interval and concurrency fields.private HostChecker.PingResultperformLeaseSetLookup(String hostname, Destination destination) Perform LeaseSet lookup as the first check Any cached LeaseSet marks the host up directly — even an expired one proves the host exists.private HostChecker.PingResultpingDestination(String hostname, Destination destination) Ping destination using single tunnel and I2Ping-style retry handling Falls back to EepHead HTTP HEAD request if ping fails, accepts leaseSetTypes parameter.private HostChecker.PingResultpingDestination(String hostname, Destination destination, String leaseSetTypes) Ping destination using single tunnel and I2Ping-style retry handling Falls back to EepHead HTTP HEAD request if ping fails, accepts leaseSetTypes parameter.private HostChecker.PingResultpingDestination(String hostname, Destination destination, String leaseSetTypes, boolean saveResult) Ping destination using single tunnel and I2Ping-style retry handling Falls back to EepHead HTTP HEAD request if ping fails, accepts leaseSetTypes parameter.private voidRefresh categories at the start of each HostChecker cycle Attempts to download fresh categories from notbob.i2p, falls back to existing file.private voidRe-read addressbook/config.txt when it changed and apply the new values live.private voidremoveFromClientTracking(Hash destHash) Remove LeaseSet from client refresh tracking after HostChecker is done with it.private voidCancel the current cycle schedule and restart it with the current interval.private HostChecker.PingResultretainRecentUp(String hostname, long now) If the host was confirmed up within the last 24h, keep it up when the current cycle can't fetch its LeaseSet - an unverifiable host is not a confirmed-down host.voidRun a host check cycle immediately, unless one is already in progress.private voidSave ping results to hosts_check.txt file.private voidSchedule periodic category download retries.voidsetUseLeaseSetCheck(boolean useLeaseSetCheck) Set whether to use LeaseSet checking.voidstart()Start periodic ping testing.voidstop()Stop periodic ping testing.testDestination(String hostname) Test a single destination immediately If LeaseSet lookup succeeds, we don't overwrite the result with failed ping/eephead.private voidUpdate hosts_check.txt with category information after successful category download.private voidwriteCleanCategoriesFile(List<String> validLines) Write cleaned categories.txt file with only valid entries (no empty lines).private voidwriteCleanHostsCheckFile(List<String> validLines) Write cleaned hosts_check.txt file with only valid entries.
Field Details
PING_TIMESTAMP_COMPARATOR
private static final Comparator<Map.Entry<String, HostChecker.PingResult>> PING_TIMESTAMP_COMPARATORSorts ping results by timestamp, oldest first._context
The app context._log
Logger for the host checks._namingService
Naming service holding the hosts to check._scheduler
Executor running the ping cycles._pingResults
Latest ping result by host name._hostCategories
_running
True while the checker is running._categoriesDownloaded
Whether the category list has been downloaded._categoriesDownloadSuccessful
Whether the last category download succeeded._cycleInProgress
True while a ping cycle is running._hostsCheckFile
File storing the ping results._categoriesFile
File storing the host categories._blacklistFile
File listing hosts never to ping._configFile
File holding the checker's settings._pingSemaphore
Limits how many hosts ping at once._blacklistedHosts
_blacklistLastModified
private volatile long _blacklistLastModifiedModification time of the blacklist file._configLastModified
private volatile long _configLastModifiedModification time of the config file._pingTaskFuture
The scheduled ping task, kept for cancellation._categoryRetryCount
private int _categoryRetryCountCategory download attempts so far._DATE_FORMAT
Per-thread date format for the result display.DEFAULT_PING_INTERVAL
private static final long DEFAULT_PING_INTERVALDefault interval between ping cycles, four hours.- See Also:
DEFAULT_PING_TIMEOUT
private static final long DEFAULT_PING_TIMEOUTDefault timeout for one ping is 60 seconds.- See Also:
DEFAULT_MAX_CONCURRENT
private static final int DEFAULT_MAX_CONCURRENTDefault hosts pinged at once.- See Also:
MAX_SHARED_PING_TUNNELS
private static final int MAX_SHARED_PING_TUNNELSCap on outbound tunnels for the shared ping session; pings are a bonus check, each tunnel costs a network build.- See Also:
KEEP_UP_MS
private static final long KEEP_UP_MSA host confirmed up within this window stays up when its LeaseSet can't be fetched this cycle.- See Also:
PROP_PING_INTERVAL
Config key for the ping cycle interval.- See Also:
PROP_MAX_CONCURRENT
Config key for the concurrent ping limit.- See Also:
STARTUP_DELAY_MS
private static final long STARTUP_DELAY_MSWait after startup before the first ping cycle.- See Also:
CATEGORY_DOWNLOAD_DELAY_MS
private static final long CATEGORY_DOWNLOAD_DELAY_MSWait before downloading the category list.- See Also:
CATEGORY_CONNECT_TIMEOUT
private static final int CATEGORY_CONNECT_TIMEOUTConnect timeout for the category download.- See Also:
CATEGORY_INACTIVITY_TIMEOUT
private static final int CATEGORY_INACTIVITY_TIMEOUTInactivity timeout for the category download.- See Also:
CATEGORY_TOTAL_TIMEOUT
private static final int CATEGORY_TOTAL_TIMEOUTTotal timeout for the category download.- See Also:
CATEGORY_RETRY_INTERVAL
private static final long CATEGORY_RETRY_INTERVALWait before retrying a failed category download.- See Also:
COMMA_SPLIT
Splits a category line on commas.PING_TASK_TIMEOUT
private static final long PING_TASK_TIMEOUTLimit on one ping cycle before it is cancelled.- See Also:
_pingInterval
private volatile long _pingIntervalPing cycle interval in effect right now._pingTimeout
private long _pingTimeoutTimeout for one ping, in effect right now._maxConcurrent
private volatile int _maxConcurrentHosts pinged at once, in effect right now._useLeaseSetCheck
private boolean _useLeaseSetCheckWhether a lease set reply counts as a successful ping.
Constructor Details
HostChecker
public HostChecker()Construct a HostChecker that uses the default naming service This works with the blockfile format (hostsdb.blockfile).HostChecker
Construct a HostChecker for given naming service.- Parameters:
namingService- naming service to test entries from
Method Details
loadConfiguration
private void loadConfiguration()Load configuration from addressbook/config.txt file Reads pingInterval and maxConcurrent properties if present.parseConfigFile
private void parseConfigFile()Parse addressbook/config.txt and update the ping interval and concurrency fields. Invalid values leave the current settings untouched.refreshConfiguration
private void refreshConfiguration()Re-read addressbook/config.txt when it changed and apply the new values live. A new interval reschedules the cycle task (next cycle only); a new concurrency limit takes effect in the in-progress cycle immediately.reschedulePingTask
private void reschedulePingTask()Cancel the current cycle schedule and restart it with the current interval. A cycle already in progress keeps running; the single-flight guard skips the next scheduled run if it would overlap.start
public void start()Start periodic ping testing.stop
public void stop()Stop periodic ping testing.runCheckNow
public void runCheckNow()Run a host check cycle immediately, unless one is already in progress. The periodic cycle schedule is unaffected.isScanRunning
public boolean isScanRunning()Whether a host check cycle is currently in progress.- Returns:
- true if a cycle is running
performLeaseSetLookup
Perform LeaseSet lookup as the first check Any cached LeaseSet marks the host up directly — even an expired one proves the host exists. Only when no LeaseSet is cached locally do we trigger a fresh remote fetch. If the lookup fails, responseTime is set to -1 and we skip ping/eephead.- Parameters:
hostname- hostname to testdestination- destination for the hostname- Returns:
- PingResult; responseTime preserves the existing value on success, -1 if the lookup failed
testDestination
Test a single destination immediately If LeaseSet lookup succeeds, we don't overwrite the result with failed ping/eephead.- Parameters:
hostname- hostname to test- Returns:
- the result recorded for this host, blacklisted hosts never pinged
lookupLeaseSetRemotely
private HostChecker.PingResult lookupLeaseSetRemotely(String hostname, Hash destHash, long startTime, long existingResponseTime) Perform remote LeaseSet lookup via floodfill network and record the result. A found LeaseSet marks the host up, keeping the previously known response time; a failed lookup retains a recent up-result or records a down-result with response time -1.- Parameters:
hostname- the host being checked, used as the result cache keydestHash- hash of the destination whose LeaseSet is fetchedstartTime- test start time in ms, used as the result timestampexistingResponseTime- last known response time in ms, or -1 if never measured- Returns:
- the recorded PingResult: up if a LeaseSet was found or a recent up-result retained, down otherwise
retainRecentUp
If the host was confirmed up within the last 24h, keep it up when the current cycle can't fetch its LeaseSet - an unverifiable host is not a confirmed-down host.- Parameters:
hostname- the host to checknow- current time for the age comparison and result timestamp- Returns:
- a fresh up-result retaining the last response time and LeaseSet types, or null when there is nothing to retain
removeFromClientTracking
Remove LeaseSet from client refresh tracking after HostChecker is done with it. This prevents unnecessary refreshes of LeaseSets that were only looked up for ping checking.- Parameters:
destHash- the destination to untrack; a null value, or a context that is not a router context, makes this a no-op
createPingSessionOptions
private static Properties createPingSessionOptions(String nickname, int inboundQuantity, int outboundQuantity) Build the I2CP options for a HostChecker ping session. Inbound tunnels only carry tiny pong replies; inboundQuantity of 1 is enough, 2 adds redundancy if a tunnel drops. The outbound quantity is caller-controlled since it scales with ping concurrency.- Parameters:
nickname- nickname for the inbound and outbound poolsinboundQuantity- number of inbound tunnels to buildoutboundQuantity- number of outbound tunnels to build- Returns:
- a fresh Properties object holding the I2CP session options, including the fixed localhost connection and LS3 encryption settings
pingDestination
Ping destination using single tunnel and I2Ping-style retry handling Falls back to EepHead HTTP HEAD request if ping fails, accepts leaseSetTypes parameter.- Parameters:
hostname- the host to ping, used as the result cache keydestination- the destination to ping- Returns:
- the PingResult from the ping, or from the EepHead fallback if the ping failed
pingDestination
private HostChecker.PingResult pingDestination(String hostname, Destination destination, String leaseSetTypes) Ping destination using single tunnel and I2Ping-style retry handling Falls back to EepHead HTTP HEAD request if ping fails, accepts leaseSetTypes parameter.- Parameters:
hostname- the host to ping, used as the result cache keydestination- the destination to pingleaseSetTypes- LeaseSet types string to carry into the result, or null for "[]"- Returns:
- the PingResult from the ping, or from the EepHead fallback if the ping failed
pingDestination
private HostChecker.PingResult pingDestination(String hostname, Destination destination, String leaseSetTypes, boolean saveResult) Ping destination using single tunnel and I2Ping-style retry handling Falls back to EepHead HTTP HEAD request if ping fails, accepts leaseSetTypes parameter.- Parameters:
hostname- the host to ping, used as the result cache keydestination- the destination to pingleaseSetTypes- LeaseSet types string to carry into the result, or null for "[]"saveResult- whether to save the result to _pingResults (false when LeaseSet lookup already succeeded)- Returns:
- the PingResult from the ping, or from the EepHead fallback when the ping failed and the result was saved
fallbackToEepHead
Fallback method to useEepHeadfor HTTP HEAD request testing Marks site as up if any response is received.- Parameters:
hostname- the host to probe, used as the result cache keystartTime- test start time in ms, used as the result timestamp- Returns:
- the PingResult: up with the HEAD round-trip time if any response was received, down with response time -1 otherwise
fallbackToEepHead
private HostChecker.PingResult fallbackToEepHead(String hostname, long startTime, String leaseSetTypes, boolean saveResult) Fallback method to use EepHead for HTTP HEAD request testing Marks site as up if any response is received.- Parameters:
hostname- the host to probe, used as the result cache keystartTime- test start time in ms, used as the result timestampleaseSetTypes- LeaseSet types string to carry into the result, or null for "[]"saveResult- whether to save the result to _pingResults (false when LeaseSet lookup already succeeded)- Returns:
- the PingResult: up with the HEAD round-trip time if any response was received, down with response time -1 otherwise
getPingResult
Get ping result for a hostname.- Parameters:
hostname- the hostname whose stored ping result is wanted- Returns:
- ping result, or null if no test has been performed
getAllPingResults
Get all ping results.- Returns:
- map of hostname to ping result
setUseLeaseSetCheck
public void setUseLeaseSetCheck(boolean useLeaseSetCheck) Set whether to use LeaseSet checking.- Parameters:
useLeaseSetCheck- true to use LeaseSet lookup first
getUseLeaseSetCheck
public boolean getUseLeaseSetCheck()Get whether to use LeaseSet checking.- Returns:
- true if LeaseSet checking is enabled
isRunning
public boolean isRunning()Check if ping tester is running.- Returns:
- true if running
loadPingResults
private void loadPingResults()Load ping results from hosts_check.txt file.savePingResults
private void savePingResults()Save ping results to hosts_check.txt file.writeCleanHostsCheckFile
Write cleaned hosts_check.txt file with only valid entries.- Parameters:
validLines- the cleaned lines to write, in order, headers included- Throws:
IOException- if the hosts_check.txt file cannot be opened or written
getDestination
Get destination for a hostname from naming service.- Parameters:
hostname- the host name to look up- Returns:
- the destination, or null if the naming service has no entry
getAllHostnames
cleanupStaleHosts
private void cleanupStaleHosts()Remove hosts from _pingResults that are no longer in the address book This prevents stale entries from accumulating in hosts_check.txt.downloadCategories
private void downloadCategories()Download categories file from notbob.i2p Falls back to existing stale categories.txt if download fails.writeCleanCategoriesFile
Write cleaned categories.txt file with only valid entries (no empty lines).- Parameters:
validLines- the cleaned lines to write, in order, headers included- Throws:
IOException- if the categories.txt file cannot be opened or written
loadCategories
private void loadCategories()Load categories from categories.txt file.getCategory
getCategoryDescription
createPingResult
private HostChecker.PingResult createPingResult(boolean reachable, long timestamp, long responseTime, String hostname) Helper method to create PingResult with category.- Parameters:
reachable- true if the host was found reachabletimestamp- time the result was recorded, in Java msresponseTime- round-trip time in ms, or -1 when not measuredhostname- used to look up the category from _hostCategories- Returns:
- PingResult with category (or null if unknown) and no leaseSetTypes
createPingResult
private HostChecker.PingResult createPingResult(boolean reachable, long timestamp, long responseTime, String hostname, String leaseSetTypes) Helper method to create PingResult with category and leaseSetTypes. An existing non-empty leaseSetTypes string is kept when the new lookup brings nothing or the same value, so a transient failure cannot erase known-good types.- Parameters:
reachable- true if the host was found reachabletimestamp- time the result was recorded, in Java msresponseTime- round-trip time in ms, or -1 when not measuredhostname- used to look up the category from _hostCategoriesleaseSetTypes- LeaseSet types string like "[6,4]", or null or "[]" to keep any previously recorded value- Returns:
- a new PingResult with the category (or null if unknown) and the effective leaseSetTypes
getAllCategories
scheduleCategoryRetries
private void scheduleCategoryRetries()Schedule periodic category download retries.attemptCategoryDownload
private boolean attemptCategoryDownload()Attempt to download categories file Returns true if successful, false otherwise.- Returns:
- true if the fetch produced at least one data line and the categories file was rewritten with it, false on any fetch, validation, or write failure
refreshCategories
private void refreshCategories()Refresh categories at the start of each HostChecker cycle Attempts to download fresh categories from notbob.i2p, falls back to existing file.updateHostsWithCategories
private void updateHostsWithCategories()Update hosts_check.txt with category information after successful category download.loadBlacklist
private void loadBlacklist()Reads the blacklisted hosts from the file.isHostBlacklisted
Checks whether a host is excluded from checking.- Parameters:
hostname- the host to check- Returns:
- true if the host is blacklisted
formatLeaseSetTypes
Format LeaseSet encryption types as a string like "[0]" or "[4,0]".- Parameters:
leaseSet- the LeaseSet to inspect, v1 or v2; a null value, or one whose encryption keys cannot be read, yields "[]"- Returns:
- the encryption type codes joined without spaces inside square brackets, or "[]" when no types were found
_t
main