java.lang.Object
net.i2p.router.CommSystemFacade
net.i2p.router.transport.CommSystemFacadeImpl
All Implemented Interfaces:
Service

public class CommSystemFacadeImplextends CommSystemFacade
Primary implementation of the communication system facade for I2P network operations.

This class provides the main interface between the router core and all transport protocols. It coordinates message sending, peer management, address configuration, and network monitoring while abstracting the underlying transport details.

Core Responsibilities:

  • Message routing and delivery across all transports
  • Peer connection management and statistics
  • Network address discovery and configuration
  • Bandwidth allocation and monitoring
  • Transport lifecycle management (start/stop/restart)
  • Network reachability testing and reporting
  • Geographic IP filtering and country blocking
  • Communication system status and health monitoring

Transport Integration:

  • Manages NTCP, UDP, and SSU transports
  • Handles transport selection and failover
  • Coordinates address updates across protocols
  • Provides unified API for router components

Configuration Features:

  • Transport enable/disable controls
  • Country-based blocking and filtering
  • Proxy configuration and detection
  • Network monitoring and testing options
  • IPv4 and IPv6 addressing support

Security Features:

  • Geographic IP filtering
  • Country-based access controls
  • Peer reputation and banlist management
  • Transport-specific security policies
  • Field Details

    • _log

      private final Log _log
      Logger for the comm system facade.
    • _context

      private final RouterContext _context
      The router context.
    • _manager

      private final TransportManager _manager
      The manager the facade reports to.
    • _geoIP

      private final GeoIP _geoIP
      The GeoIP lookup helper.
    • _rdns

      private final ReverseDnsLookup _rdns
      The reverse DNS lookup helper.
    • _countryLookup

      private final CountryLookup _countryLookup
      The country name lookup helper.
    • _peerHTML

      private final PeerHTMLRenderer _peerHTML
      Renderer of the peer detail pages.
    • _exemptIncoming

      private final Map<String,Object> _exemptIncoming
      Peers exempt from the incoming rate limits.
    • _netMonitorStatus

      private volatile boolean _netMonitorStatus
      True while the network monitoring is enabled.
    • _wasStarted

      private boolean _wasStarted
      True once the transports were started.
    • PROP_DISABLED

      private static final String PROP_DISABLED
      Property to disable all network connections for testing purposes.

      When this property is set to true, the communication system will not establish any outbound connections or accept inbound connections. This is useful for testing scenarios or when running in debug mode.

      See Also:
    • DUMMY

      private static final Object DUMMY
      Placeholder value for the exempt peer sets.
    • TIME_START_DELAY

      private static final int TIME_START_DELAY
      Startup delay before the first status ping.
      See Also:
    • TIME_REPEAT_DELAY

      private static final int TIME_REPEAT_DELAY
      Interval between the status pings.
      See Also:
  • Constructor Details

    • CommSystemFacadeImpl

      public CommSystemFacadeImpl(RouterContext context)
      Build the transport manager, GeoIP database and address lookup services.
      Parameters:
      context - the router context, used to build the transport manager, GeoIP database and rDNS/country lookup services
  • Method Details

    • getRdnsCorePoolSize

      public static int getRdnsCorePoolSize()
      The rDNS executor core pool size.
      Returns:
      the number of threads currently in the rDNS core pool
    • setRdnsCorePoolSize

      public static void setRdnsCorePoolSize(int size)
      The rDNS executor core pool size, bounded 2-8.
      Parameters:
      size - the requested core pool size, clamped by rDNS to 2-8
    • getRdnsMaxPoolSize

      public static int getRdnsMaxPoolSize()
      The rDNS executor max pool size.
      Returns:
      the upper bound on rDNS executor threads
    • setRdnsMaxPoolSize

      public static void setRdnsMaxPoolSize(int size)
      The rDNS executor max pool size, bounded 2-8.
      Parameters:
      size - the requested maximum pool size, clamped by rDNS to 2-8
    • rdnsCacheSize

      public static String rdnsCacheSize()
      The size of the rDNS cache file, in KB.
      Returns:
      the on-disk size of the rDNS cache, in kilobytes
    • countRdnsCacheEntries

      public static int countRdnsCacheEntries()
      The number of entries in the rDNS cache.
      Returns:
      how many hostnames are currently held in the rDNS cache
    • getRdnsCacheStats

      public static String getRdnsCacheStats()
      Cache statistics for monitoring.
      Returns:
      formatted string with cache stats
    • getMaxRdnsCacheSize

      public static int getMaxRdnsCacheSize()
      The maximum rDNS cache size, computed from the memory available.
      Returns:
      the entries the cache holds
    • adjustRdnsPool

      public void adjustRdnsPool(int coreSize)
      Adjust the running rDNS executor pool sizes. Called by the Tuner when queue depth signals scaling.
      Parameters:
      coreSize - new core pool size (bounded 2-8)
    • getRdnsQueueSize

      public int getRdnsQueueSize()
      Returns rDNS executor pending lookup count, or 0 if not running.
      Returns:
      the rdns queue size
    • getRdnsActiveCount

      public int getRdnsActiveCount()
      Returns rDNS executor active thread count, or 0 if not running.
      Returns:
      the rdns active count
    • getRdnsPoolSize

      public int getRdnsPoolSize()
      Returns rDNS executor total thread count, or 0 if not running.
      Returns:
      the rdns pool size
    • getRdnsUtilization

      public double getRdnsUtilization()
      Returns rDNS executor utilization as a ratio (0.0-1.0), or Double.NaN if not running.
      Returns:
      the rdns utilization
    • enableReverseLookups

      public boolean enableReverseLookups()
      Whether reverse lookups are enabled.
      Specified by:
      enableReverseLookups in class CommSystemFacade
      Returns:
      true if reverse lookups are enabled
    • getCanonicalHostName

      public String getCanonicalHostName(String ipAddress)
      Canonical hostname for the given IP address from cache or DNS. If RDNS is enabled, performs a reverse DNS lookup first. Falls back to local ASN database if DNS fails, returning the org name.
      Overrides:
      getCanonicalHostName in class CommSystemFacade
      Parameters:
      ipAddress - IP address to resolve, or null/"null" to return null
      Returns:
      hostname, org name from ASN database, or null for invalid input
    • getCanonicalHostNameSync

      public String getCanonicalHostNameSync(String ipAddress)
      The canonical host name for the given IP address, resolved synchronously.
      Overrides:
      getCanonicalHostNameSync in class CommSystemFacade
      Parameters:
      ipAddress - the IP address to look up
      Returns:
      the canonical host name
    • getLocalHostName

      public String getLocalHostName(String ipAddress)
      Fast hostname lookup that never blocks on I/O (MMDB or network). Returns cached result if available and useful. On cache miss, queues a background job that does ASN org name lookup (MMDB file read + regex normalization) and optional RDNS, then returns null immediately — page rendering is never blocked.
      Overrides:
      getLocalHostName in class CommSystemFacade
      Parameters:
      ipAddress - the address to resolve, as text
      Returns:
      cached hostname/ASN org name, or null if not yet resolved
    • startup

      public void startup()
      Start the communication system and all transport protocols.

      This method initializes the communication system, starts all configured transports, and begins network operations. It handles transport discovery, address configuration, and peer management setup.

      Startup Process:

      • Initialize geographic IP filtering
      • Start network monitoring
      • Register and start all configured transports
      • Begin peer discovery and connection attempts
      • Setup address change notifications
      Throws:
      IllegalStateException - if already running
    • shutdown

      public void shutdown()
      Cannot be restarted after calling this. Use restart() for that.

      Gracefully shutdown the communication system.

      This method performs a clean shutdown of all transport protocols and network operations. It stops accepting new connections, closes existing ones, and performs cleanup of system resources.

      Shutdown Process:

      • Stop network monitoring
      • Stop all transport protocols
      • Close all active connections
      • Cleanup system resources and caches
      • Save final state and statistics
      Throws:
      IllegalStateException - if not running
    • restart

      public void restart()
      Restart the communication system.

      This method performs a complete restart of all transport protocols while preserving router state. It stops all transports, reinitializes system components, and restarts network operations.

      Restart Process:

      • Stop all transport protocols gracefully
      • Reinitialize system components
      • Restart transports with preserved state
      • Resume network operations and monitoring
      • Reconfigure address management
      Throws:
      IllegalStateException - if not running
    • isRunning

      public boolean isRunning()
      Whether the comm system is running.
      Overrides:
      isRunning in class CommSystemFacade
      Returns:
      true if start() has been called and not stopped or restarted
    • countActivePeers

      public int countActivePeers()
      How many peers are we currently connected to, that we have sent a message to or received a message from in the last minute.
      Specified by:
      countActivePeers in class CommSystemFacade
      Returns:
      the number of active peers
    • countActiveSendPeers

      public int countActiveSendPeers()
      How many peers we have sent a message to in the last minute.

      Narrower than CommSystemFacade.countActivePeers() in both respects that matter: send only, and a one-minute window rather than the transport's active window. The pair answers different questions - how many peers we can reach against how many we are actually driving traffic to right now.

      The javadoc on this method said "in the last minute" already, while countActivePeers() above it says five. Only the latter is inaccurate: every transport's active window is sixty seconds. The send-only count is the one this declares, per transport.

      Specified by:
      countActiveSendPeers in class CommSystemFacade
      Returns:
      the number of peers sent to in the last minute
    • haveInboundCapacity

      public boolean haveInboundCapacity(int pct)
      Whether we have capacity to handle an inbound message at the given percentage.
      Overrides:
      haveInboundCapacity in class CommSystemFacade
      Parameters:
      pct - percentage of bandwidth currently in use
      Returns:
      true if capacity is available
    • haveOutboundCapacity

      public boolean haveOutboundCapacity(int pct)
      Whether we have capacity to handle an outbound message at the given percentage.
      Overrides:
      haveOutboundCapacity in class CommSystemFacade
      Parameters:
      pct - percentage of bandwidth currently in use
      Returns:
      true if capacity is available
    • haveHighOutboundCapacity

      public boolean haveHighOutboundCapacity()
      Whether we have high outbound capacity.
      Overrides:
      haveHighOutboundCapacity in class CommSystemFacade
      Returns:
      true if high outbound capacity is available
    • getFramedAveragePeerClockSkew

      public long getFramedAveragePeerClockSkew(int percentToInclude)
      The framed average clock skew of connected peers in milliseconds, or the clock offset if we cannot answer. A positive number means our clock is ahead of theirs. Todo: change List to milliseconds.
      Overrides:
      getFramedAveragePeerClockSkew in class CommSystemFacade
      Parameters:
      percentToInclude - 1-100
      Returns:
      The framed average clock skew of connected peers in milliseconds, or the clock offset if we cannot answer. Average is calculated over the middle "percentToInclude" peers.
    • processMessage

      public void processMessage(OutNetMessage msg)
      Process and route an outbound message through the transport system.

      This method is the central entry point for sending messages to other I2P peers. It selects appropriate transport, handles message queuing, and manages delivery tracking.

      Message Processing:

      • Transport selection based on destination
      • Message validation and filtering
      • Queueing and throttling
      • Delivery status tracking
      • Failure handling and retry logic
      • Callback execution for send completion
      Specified by:
      processMessage in class CommSystemFacade
      Parameters:
      msg - the outbound message to be processed and delivered
    • isBacklogged

      public boolean isBacklogged(Hash peer)
      Whether the given peer is backlogged.
      Overrides:
      isBacklogged in class CommSystemFacade
      Parameters:
      peer - the router to test, identified by its router identity hash
      Returns:
      true if we have messages queued for the peer, awaiting responses
    • isEstablished

      public boolean isEstablished(Hash peer)
      Whether the given peer is established.
      Specified by:
      isEstablished in class CommSystemFacade
      Parameters:
      peer - the router to test, identified by its router identity hash
      Returns:
      true if the transport session to the peer is up
    • wasFailsafeClosed

      public boolean wasFailsafeClosed(Hash peer, long withinMs)
      Whether the peer's most recent connection was closed by the failsafe.
      Specified by:
      wasFailsafeClosed in class CommSystemFacade
      Parameters:
      peer - the peer to ask about, non-null
      withinMs - how far back counts as recent in ms; non-positive means nothing is recent
      Returns:
      true when some transport closed a session to the peer that recently
    • getEstablished

      public List<Hash> getEstablished()
      Established peers.
      Specified by:
      getEstablished in class CommSystemFacade
      Returns:
      a new list, may be modified
    • wasUnreachable

      public boolean wasUnreachable(Hash peer)
      Whether the given peer was recently unreachable.
      Overrides:
      wasUnreachable in class CommSystemFacade
      Parameters:
      peer - the router to test, identified by its router identity hash
      Returns:
      true if the peer was unreachable
    • isConnecting

      public boolean isConnecting(Hash peer)
      Whether we are currently connecting to the given peer.
      Overrides:
      isConnecting in class CommSystemFacade
      Parameters:
      peer - hash of the peer to check
      Returns:
      true if a connection attempt to the peer is in progress
    • getIP

      public byte[] getIP(Hash peer)
      The known IP address of the given peer.
      Overrides:
      getIP in class CommSystemFacade
      Parameters:
      peer - the destination hash to resolve; no entry means null is returned
      Returns:
      the IP address
    • mayDisconnect

      public void mayDisconnect(Hash peer)
      Tell the comm system that we may disconnect from this peer. This is advisory only.
      Overrides:
      mayDisconnect in class CommSystemFacade
      Parameters:
      peer - the peer we may drop
    • forceDisconnect

      public void forceDisconnect(Hash peer)
      Tell the comm system to disconnect from this peer.
      Overrides:
      forceDisconnect in class CommSystemFacade
      Parameters:
      peer - the peer to disconnect from
    • forceDisconnect

      public void forceDisconnect(Hash peer, String reason)
      Force an immediate disconnect from the given peer with the given reason.
      Overrides:
      forceDisconnect in class CommSystemFacade
      Parameters:
      peer - the router to disconnect from, identified by its router identity hash
      reason - reason for disconnection (for logging), may be null
    • getMostRecentErrorMessages

      public List<String> getMostRecentErrorMessages()
      The status of the communication system.
      Overrides:
      getMostRecentErrorMessages in class CommSystemFacade
      Returns:
      most recent error messages, most recent first
    • getStatus

      public CommSystemFacade.Status getStatus()
      The current network status.
      Overrides:
      getStatus in class CommSystemFacade
      Returns:
      the router reachability status
    • getLocalizedStatusString

      public String getLocalizedStatusString()
      The localized status string from getStatus().toStatusString(), translated if available.
      Overrides:
      getLocalizedStatusString in class CommSystemFacade
      Returns:
      the localized status string
    • renderStatusHTML

      public void renderStatusHTML(Writer out, String urlBase, int sortFlags) throws IOException
      Render the status of the transport manager to the console as HTML.

      As of 0.9.31, only outputs UPnP status.

      Warning - blocking, very slow, queries the active UPnP router, will take many seconds if it has vanished.

      Overrides:
      renderStatusHTML in class CommSystemFacade
      Parameters:
      out - receives the HTML for this transport's status section
      urlBase - base URL for links, may be null
      sortFlags - flags controlling sort order
      Throws:
      IOException - on write error
    • getTransports

      public SortedMap<String, Transport> getTransports()
      Transports in use.
      Overrides:
      getTransports in class CommSystemFacade
      Returns:
      SortedMap of style to Transport (a copy)
    • createAddresses

      public List<RouterAddress> createAddresses()
      Create router addresses for all configured transport protocols.

      This method generates RouterAddress objects for each transport protocol based on current configuration and network conditions. It handles address discovery, validation, and format conversion.

      Address Creation:

      • Iterates through all registered transports
      • Gets current addresses from each transport
      • Validates address format and consistency
      • Handles IPv4 and IPv6 address generation
      • Applies geographic and network filtering
      Overrides:
      createAddresses in class CommSystemFacade
      Returns:
      list of RouterAddress objects for all active transports, may be empty if no addresses available
    • notifyReplaceAddress

      public void notifyReplaceAddress(RouterAddress udpAddr)
      UDP changed addresses, tell NTCP and restart All the work moved to NTCPTransport.externalAddressReceived(Transport.AddressSource, byte[], int).
      Overrides:
      notifyReplaceAddress in class CommSystemFacade
      Parameters:
      udpAddr - may be null; or udpAddr's host/IP may be null
    • notifyRemoveAddress

      public void notifyRemoveAddress(RouterAddress address)
      Tell other transports our address changed.
      Overrides:
      notifyRemoveAddress in class CommSystemFacade
      Parameters:
      address - may be null; or address's host/IP may be null
    • notifyRemoveAddress

      public void notifyRemoveAddress(boolean ipv6)
      Tell other transports our address changed.
      Overrides:
      notifyRemoveAddress in class CommSystemFacade
      Parameters:
      ipv6 - true to remove the IPv6 address, false for IPv4
    • exemptIncoming

      public void exemptIncoming(Hash peer)
      Exempt this router hash from any incoming throttles or rejections.
      Overrides:
      exemptIncoming in class CommSystemFacade
      Parameters:
      peer - the router to exempt
    • isExemptIncoming

      public boolean isExemptIncoming(String ip)
      Is this IP exempt from any incoming throttles or rejections.
      Overrides:
      isExemptIncoming in class CommSystemFacade
      Parameters:
      ip - canonical string
      Returns:
      whether exempt incoming
    • removeExemption

      public void removeExemption(String ip)
      Remove this IP from the exemptions.
      Overrides:
      removeExemption in class CommSystemFacade
      Parameters:
      ip - canonical string
    • registerTransport

      public void registerTransport(Transport t)
      Pluggable transports. Not for NTCP or SSU.

      Do not call from transport constructor. Transport must be ready to be started.

      Following transport methods will be called: setListener() externalAddressReceived() (zero or more times, one for each known address) startListening();

      Overrides:
      registerTransport in class CommSystemFacade
      Parameters:
      t - the transport to register
    • unregisterTransport

      public void unregisterTransport(Transport t)
      Pluggable transports. Not for NTCP or SSU.

      Following transport methods will be called: setListener(null) stopListening();

      Overrides:
      unregisterTransport in class CommSystemFacade
      Parameters:
      t - the transport to unregister
    • getXDHFactory

      public X25519KeyFactory getXDHFactory()
      Factory for making X25519 key pairs.
      Overrides:
      getXDHFactory in class CommSystemFacade
      Returns:
      the XDHE factory
    • initGeoIP

      public void initGeoIP()
      Router must call after netdb is initialized.
      Overrides:
      initGeoIP in class CommSystemFacade
    • startGeoIP

      private void startGeoIP()
      Router must call after netdb is initialized. Starts the recurring country-lookup pipeline; the reverse-DNS cache file is loaded once the GeoIP queue has had a chance to settle.
    • getOurCountry

      public String getOurCountry()
      Country code for this router, from the GeoIP lookup.
      Overrides:
      getOurCountry in class CommSystemFacade
      Returns:
      two-letter lower-case country code or null
    • isInStrictCountry

      public boolean isInStrictCountry()
      Are we in a strict country.
      Overrides:
      isInStrictCountry in class CommSystemFacade
      Returns:
      whether in strict country
    • isInStrictCountry

      public boolean isInStrictCountry(Hash peer)
      Are they in a strict country.
      Overrides:
      isInStrictCountry in class CommSystemFacade
      Parameters:
      peer - hash of the peer to look up
      Returns:
      whether in strict country
    • isInStrictCountry

      public boolean isInStrictCountry(RouterInfo ri)
      Are they in a strict country.
      Overrides:
      isInStrictCountry in class CommSystemFacade
      Parameters:
      ri - RouterInfo of the peer, used for IP extraction
      Returns:
      whether in strict country
    • getCountry

      public String getCountry(Hash peer)
      Uses the transport IP first because that lookup is fast, then the IP from the netDb. Not recommended for our local router hash, as we may not be either in the cache or netdb, or may not be publishing an IP.

      As of 0.9.32, works only for literal IPs, returns null for hostnames.

      Overrides:
      getCountry in class CommSystemFacade
      Parameters:
      peer - not ourselves - use getOurCountry() for that
      Returns:
      two-letter lower-case country code or xx for non-banned peers, or null otherwise
    • getCountry

      public String getCountry(String ip)
      The two-letter country code for an IP address string.
      Overrides:
      getCountry in class CommSystemFacade
      Parameters:
      ip - IP address string
      Returns:
      two-letter country code or null if unknown
    • getCountryName

      public String getCountryName(String c)
      Full name for a country code.
      Overrides:
      getCountryName in class CommSystemFacade
      Parameters:
      c - the two letter country code to resolve
      Returns:
      full name or the code if unknown
    • getCountries

      public Map<String,String> getCountries()
      Provides country code mappings.
      Overrides:
      getCountries in class CommSystemFacade
      Returns:
      Unmodifiable map of lower-case country codes to untranslated names
    • queueLookup

      public void queueLookup(byte[] ip)
      Queue all current destination for lookup. For internal use only.
      Overrides:
      queueLookup in class CommSystemFacade
      Parameters:
      ip - full 128 bit ip address
    • getDomain

      public static String getDomain(String hostname)
      Domain name from a reverse DNS hostname.
      Parameters:
      hostname - the reverse DNS hostname, whose leading labels are stripped down to the registrable domain
      Returns:
      domain name only from reverse dns hostname lookups
    • getValidIP

      public static byte[] getValidIP(RouterInfo ri)
      Return first valid IP (v4 or v6) we find, any transport.
      Parameters:
      ri - RouterInfo whose addresses are examined in order until one parses as a valid address
      Returns:
      IP or null
    • getCompatibleIP

      public static byte[] getCompatibleIP(RouterInfo ri)
      IP address compatible with our capabilities (IPv4/IPv6).
      Parameters:
      ri - RouterInfo to get IP from
      Returns:
      IP or null
    • renderPeerHTML

      public String renderPeerHTML(Hash peer, boolean extended)
      Renders HTML for a peer with optional extended info. Uses cached RouterInfo, country info, and reverse lookup cache.
      Overrides:
      renderPeerHTML in class CommSystemFacade
      Parameters:
      peer - hash of the peer to render
      extended - Whether to show extended capabilities
      Returns:
      HTML snippet representing peer
    • renderPeerFlag

      public String renderPeerFlag(Hash peer)
      Render the HTML flag image for the given peer.
      Overrides:
      renderPeerFlag in class CommSystemFacade
      Parameters:
      peer - the router whose country is shown, identified by its router identity hash
      Returns:
      HTML string for the flag
    • renderPeerCaps

      public String renderPeerCaps(Hash peer, boolean inline)
      Renders the peer's capability HTML block. Caches data and removes unnecessary repeated computation.
      Overrides:
      renderPeerCaps in class CommSystemFacade
      Parameters:
      peer - hash of the peer to render
      inline - If true, render inline without table wrapper
      Returns:
      HTML snippet of peer capabilities
    • isDummy

      public boolean isDummy()
      Is everything disabled for testing?
      Overrides:
      isDummy in class CommSystemFacade
      Returns:
      true if the i2np.disable property is set
    • startTimestamper

      private void startTimestamper()
      Start the backup timestamper.
    • startNetMonitor

      private void startNetMonitor()
      Start the network monitor.