All Implemented Interfaces:
Logging, EventDispatcher

public class I2PTunnelextends EventDispatcherImpl implements Logging
Manages I2PTunnelTasks and I2PSessions. Typically one of each.
  • Field Details

    • _log

      private final Log _log
      Logger for the tunnel.
    • _context

      private final I2PAppContext _context
      The app context.
    • __tunnelId

      private static final AtomicLong __tunnelId
      Sequence number of the created tunnels.
    • _tunnelId

      private final long _tunnelId
      This tunnel's position in that sequence.
    • _clientOptions

      private final Properties _clientOptions
      The I2CP options of the tunnel.
    • _sessions

      private final Set<I2PSession> _sessions
      The sessions the tunnel holds open.
    • _controller

      private final TunnelController _controller
      The controller that started the tunnel.
    • PACKET_DELAY

      public static final int PACKET_DELAY
      Packet processing delay in milliseconds.
      See Also:
    • ownDest

      public volatile boolean ownDest
      Whether to use own destination.
    • port

      public String port
      The I2CP port, non-null.
    • host

      public String host
      The I2CP host, non-null.
    • listenHost

      public String listenHost
      The listen-on host. Sadly the listen-on port does not have a field.
    • readTimeout

      public long readTimeout
      Default read timeout for tunnel connections (-1 = no timeout).
    • filterDefinition

      public String filterDefinition
      Absolute path to filter definition file.
    • nocli_args

      private static final String[] nocli_args
      Arguments hidden from the command line help.
    • tasks

      private final List<I2PTunnelTask> tasks
      The tasks serving the connections.
    • next_task_id

      private int next_task_id
      Id given to the next task.
    • listeners

      private final Set<I2PTunnel.ConnectionEventListener> listeners
      Listeners of the connection events.
    • NOGUI

      private static final int NOGUI
      Port meaning the standalone app has no console.
      See Also:
    • longopts

      private static final LongOpt[] longopts
      The command line options of the standalone app.
  • Constructor Details

    • I2PTunnel

      public I2PTunnel()
      Standard constructor for embedded, uses args "-nocli -die" to return immediately.
    • I2PTunnel

      public I2PTunnel(TunnelController tc)
      New standard constructor in router, with back ref to tc.
      Parameters:
      tc - may be null
      Throws:
      IllegalArgumentException - if the arguments are unparseable, name more than one command, or the trailing command file does not exist
    • I2PTunnel

      public I2PTunnel(String[] args)
      See usage() for options.
      Parameters:
      args - the CLI arguments, parsed per usage()
      Throws:
      IllegalArgumentException - if the arguments are unparseable, name more than one command, or the trailing command file does not exist
    • I2PTunnel

      public I2PTunnel(String[] args, I2PTunnel.ConnectionEventListener lsnr)
      See usage() for options.
      Parameters:
      args - the CLI arguments, parsed per usage()
      lsnr - may be null
      Throws:
      IllegalArgumentException - if the arguments are unparseable, name more than one command, or the trailing command file does not exist
    • I2PTunnel

      private I2PTunnel(String[] args, I2PTunnel.ConnectionEventListener lsnr, TunnelController tc)
      Creates the tunnel with its listener and controller.
      Parameters:
      args - the command-line arguments, parsed for the option letters and a trailing command file
      lsnr - may be null
      tc - may be null
      Throws:
      IllegalArgumentException - if the options are unparseable, or the command file named at the end of the arguments does not exist
  • Method Details

    • main

      public static void main(String[] args)
      Command-line entry point.
      Parameters:
      args - the command-line arguments parsed by the I2PTunnel constructor
    • runGUI

      private void runGUI()
      Launch the GUI, exiting if it is not available.
    • runCLI

      private void runCLI()
      Run an interactive command-line interface on stdin.
    • usage

      private static String usage()
      The command-line usage text, one option per line.
      Returns:
      the usage text, with newlines except for last line
    • getTasks

      public List<I2PTunnelTask> getTasks()
      Snapshot of the running tasks.
      Returns:
      an unmodifiable snapshot, non-null; changes to the tunnel's task list are not reflected in an already-returned list
    • getSessions

      public List<I2PSession> getSessions()
      Snapshot of the primary sessions in use by this tunnel's tasks. Subsessions are not tracked here; a task's own getSocketManager() remains the way to reach them.
      Returns:
      an unmodifiable snapshot, non-null; changes to the tunnel's session set are not reflected in an already-returned list. The iteration order follows the underlying set and is not specified.
    • addSession

      void addSession(I2PSession session)
      Add a session to the tunnel.
      Parameters:
      session - null ok
    • removeSession

      void removeSession(I2PSession session)
      Remove a session from the tunnel.
      Parameters:
      session - null ok
    • getClientOptions

      public Properties getClientOptions()
      Generic options used for clients and servers. NOT a copy, Do NOT modify for per-connection options, make a copy.
      Returns:
      non-null, NOT a copy, do NOT modify for per-connection options
    • getController

      TunnelController getController()
      TunnelController that constructed this, or null.
      Returns:
      controller or null
    • addtask

      private void addtask(I2PTunnelTask tsk)
      Adds a task serving the connections.
      Parameters:
      tsk - the task to add
    • split

      private static String[] split(String src, String delim)
      Java 1.3 vs 1.4 :).
      Parameters:
      src - the string to break into tokens
      delim - the characters that separate tokens, any one of which splits, and runs of them produce no empty tokens
      Returns:
      the tokens in order, an empty array when there are none
    • runCommand

      public void runCommand(String cmd, Logging l)
      Parses and executes a tunnel management command.

      This method is the command dispatcher for tunnel management operations. It parses the command string into command name and arguments, then dispatches to the appropriate handler method.

      Supported Commands:

      • help - Display available commands
      • client/server - Create tunnel instances
      • list - List active tunnels
      • close - Close tunnels
      • config - Configure I2CP connection
      • genkeys - Generate destination keys
      Parameters:
      cmd - the command string to execute, format: "commandName arg1 arg2 ..."
      l - the Logging instance for command output
      See Also:
    • clientRunError

      private void clientRunError(String msg, String taskId, Logging l, IllegalArgumentException iae)
      Log a failed client tunnel configuration and propagate the error.
      Parameters:
      msg - the error message
      taskId - the event name for the failed tunnel type
      l - logger to receive events and output
      iae - the configuration error
    • parseServerHost

      private InetAddress parseServerHost(String hostArg, Logging l)
      Resolve a server host argument.
      Parameters:
      hostArg - the hostname argument
      l - logger to receive events and output
      Returns:
      the resolved address
      Throws:
      IllegalArgumentException - if the host cannot be resolved
    • parseServerPort

      private int parseServerPort(String portArg, Logging l)
      Parse a server port argument.
      Parameters:
      portArg - the port argument
      l - logger to receive events and output
      Returns:
      the parsed port
      Throws:
      IllegalArgumentException - if the port is not a valid positive integer
    • getPrivKeyFile

      private File getPrivKeyFile(String fileArg, Logging l)
      Resolve a private key file argument relative to the config dir.
      Parameters:
      fileArg - the key file argument
      l - logger to receive events and output
      Returns:
      the readable key file
      Throws:
      IllegalArgumentException - if the file does not exist or is not readable
    • runHelp

      private static void runHelp(Logging l)
      Display help information through the given logger.

      Does not fire any events to the logger.

      Parameters:
      l - logger to receive events and output
    • runClientOptions

      public void runClientOptions(String[] args, Logging l)
      Configure the extra I2CP options to use in any subsequent I2CP sessions. Generic options used for clients and servers Usage: "clientoptions[ key=value]*" .

      Event "clientoptions_onResult" = "ok" on completion.

      Deprecated To be made private, use setClientOptions(Properties). This does NOT update a running TunnelTask.

      Parameters:
      args - each args[i] is a key=value pair to add to the options
      l - logger to receive events and output
    • setClientOptions

      public void setClientOptions(Properties opts)
      Generic options used for clients and servers. This DOES update a running TunnelTask, but NOT the session. A more efficient runClientOptions(String[], Logging).

      Defaults in opts properties are not recommended, they may or may not be honored.

      Parameters:
      opts - non-null
    • runServer

      public void runServer(String[] args, Logging l)
      Run the server pointing at the host and port specified using the private i2p destination loaded from the specified file.

      Event "serverTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error) Also sets the event "openServerResult" = "ok" or "error" (displaying "Ready!" on the logger after 'ok'). So, success = serverTaskId != -1 and openServerResult = ok.

      Parameters:
      args - {hostname, portNumber, privKeyFilename}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runIrcServer

      public void runIrcServer(String[] args, Logging l)
      Same args as runServer (we should stop duplicating all this code...).
      Parameters:
      args - host, port and privkeyfile, exactly as runServer takes them
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runHttpServer

      public void runHttpServer(String[] args, Logging l)
      Run the HTTP server pointing at the host and port specified using the private i2p destination loaded from the specified file, replacing the HTTP headers so that the Host: specified is the one spoofed.

      Event "serverTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error) Also sets the event "openServerResult" = "ok" or "error" (displaying "Ready!" on the logger after 'ok'). So, success = serverTaskId != -1 and openServerResult = ok.

      Parameters:
      args - {hostname, portNumber, spoofedHost, privKeyFilename}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runHttpBidirServer

      public void runHttpBidirServer(String[] args, Logging l)
      Run the HTTP server pointing at the host and port specified using the private i2p destination loaded from the specified file, replacing the HTTP headers so that the Host: specified is the one spoofed. Also runs an HTTP proxy for bidirectional communications on the same tunnel destination.

      Event "serverTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error) Also sets the event "openServerResult" = "ok" or "error" (displaying "Ready!" on the logger after 'ok'). So, success = serverTaskId != -1 and openServerResult = ok.

      Parameters:
      args - {hostname, portNumber, proxyPortNumber, spoofedHost, privKeyFilename}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runTextServer

      public void runTextServer(String[] args, Logging l)
      Run the server pointing at the host and port specified using the private i2p destination loaded from the given base64 stream.

      Deprecated? Why run a server with a private destination? Not available from the war GUI

      Event "serverTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error) Also sets the event "openServerResult" = "ok" or "error" (displaying "Ready!" on the logger after 'ok'). So, success = serverTaskId != -1 and openServerResult = ok.

      Parameters:
      args - {hostname, portNumber, privKeyBase64}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runClient

      public void runClient(String[] args, Logging l)
      Run the client on the given port number pointing at the specified destination (either the base64 of the destination or file:fileNameContainingDestination).

      Event "clientTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error) Also sets the event "openClientResult" = "error" or "ok" (before setting the value to "ok" it also adds "Ready! Port #" to the logger as well). In addition, it will also set "clientLocalPort" = Integer port number if the client is listening sharedClient parameter is a String "true" or "false".

      Parameters:
      args - {portNumber, destinationBase64 or "file:filename"[, sharedClient [, privKeyFile]]}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runHttpClient

      public void runHttpClient(String[] args, Logging l)
      Run an HTTP client on the given port number

      Event "httpclientTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error). Also sets "httpclientStatus" = "ok" or "error" after the client tunnel has started. parameter sharedClient is a String, either "true" or "false".

      Parameters:
      args - {portNumber[, sharedClient][, proxy to be used for the WWW]}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runConnectClient

      public void runConnectClient(String[] args, Logging l)
      Run a CONNECT client on the given port number

      Event "connectclientTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error).

      Parameters:
      args - {portNumber[, sharedClient][, proxy to be used for the WWW]}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runIrcClient

      public void runIrcClient(String[] args, Logging l)
      Run an IRC client on the given port number

      Event "ircclientTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error). Also sets "ircclientStatus" = "ok" or "error" after the client tunnel has started. parameter sharedClient is a String, either "true" or "false".

      Parameters:
      args - {portNumber,destinationBase64 or "file:filename" [, sharedClient [, privKeyFile]]}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runSOCKSTunnel

      public void runSOCKSTunnel(String[] args, Logging l)
      Run an SOCKS tunnel on the given port number

      Event "sockstunnelTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error). Also sets "openSOCKSTunnelResult" = "ok" or "error" after the client tunnel has started.

      Parameters:
      args - {portNumber [, sharedClient]} or (portNumber, ignored (false), privKeyFile)
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runSOCKSIRCTunnel

      public void runSOCKSIRCTunnel(String[] args, Logging l)
      Run an SOCKS IRC tunnel on the given port number

      Event "socksirctunnelTaskId" = Integer(taskId) after the tunnel has been started (or -1 on error).

      Parameters:
      args - {portNumber [, sharedClient]} or (portNumber, ignored (false), privKeyFile)
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runStreamrClient

      public void runStreamrClient(String[] args, Logging l)
      Streamr client.
      Parameters:
      args - {targethost, targetport, destinationString}
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runStreamrServer

      public void runStreamrServer(String[] args, Logging l)
      Streamr server.
      Parameters:
      args - exactly two: the port and the private key file, which is resolved against the config dir when not absolute
      l - logger to receive events and output
      Throws:
      IllegalArgumentException - on config problem
    • runConfig

      private void runConfig(String[] args, Logging l)
      Specify the i2cp host and port Deprecated - only used by CLI

      Event "configResult" = "ok" or "error" after the configuration has been specified.

      Parameters:
      args - an optional leading -s for SSL, then the I2CP host and port
      l - logger to receive events and output
    • runAuth

      private void runAuth(String[] args, Logging l)
      Specify the i2cp username and password.
      Parameters:
      args - exactly two: the I2CP username and password
      l - logger to receive events and output
    • runOwnDest

      private void runOwnDest(String[] args, Logging l)
      Specify whether to use its own destination for each outgoing tunnel Deprecated - only used by CLI

      Event "owndestResult" = "ok" or "error" after the configuration has been specified.

      Parameters:
      args - {yes or no}
      l - logger to receive events and output
    • runListenOn

      public void runListenOn(String[] args, Logging l)
      Specify the hostname / IP address of the interface that the tunnels should bind to

      Event "listen_onResult" = "ok" or "error" after the interface has been specified.

      Parameters:
      args - exactly one: the interface hostname or IP to bind to
      l - logger to receive events and output
    • runReadTimeout

      public void runReadTimeout(String[] args, Logging l)
      Specify the read timeout going to be used for newly-created I2PSockets

      Event "read_timeoutResult" = "ok" or "error" after the interface has been specified.

      Parameters:
      args - exactly one: the read timeout in ms; negative waits forever
      l - logger to receive events and output
    • runGenKeys

      private static void runGenKeys(String[] args, Logging l)
      Generate a new keypair. Does NOT support non-default sig types. Deprecated - only used by CLI

      Event "genkeysResult" = "ok" or "error" after the generation is complete.

      Parameters:
      args - {privateKeyFilename, publicKeyFilename} or {privateKeyFilename}
      l - logger to receive events and output
    • runGenTextKeys

      private static void runGenTextKeys(Logging l)
      Generate a new keypair. Does NOT support non-default sig types. Deprecated - only used by CLI

      Event "privateKey" = base64 of the privateKey stream and sets the event "publicDestination" = base64 of the destination.

      Parameters:
      l - logger to receive events and output
    • runQuit

      private void runQuit(Logging l)
      Exit the JVM if there are no more tasks left running. If there are tunnels running, it returns. Deprecated - only used by CLI

      Event "quitResult" = "error" if there are tasks running (but if there aren't, well, there's no point in setting the quitResult to "ok", now is there?).

      Parameters:
      l - logger to receive events and output
    • runList

      private void runList(Logging l)
      Retrieve a list of currently running tasks Deprecated - only used by CLI

      Event "listDone" = "done" after dumping the tasks to the logger.

      Parameters:
      l - logger to receive events and output
    • runClose

      public void runClose(String[] args, Logging l)
      Close the given task (or all tasks), optionally forcing them to die a hard death

      Event "closeResult" = "ok" after the closing is complete.

      Parameters:
      args - {jobNumber}, {"forced", jobNumber}, {"forced", "all"}, {"destroy", jobNumber}, {"destroy", "all"}
      l - logger to receive events and output
    • runRun

      private void runRun(String[] args, Logging l)
      Run all of the commands in the given file (one command per line) Deprecated - only used by CLI

      Event "runResult" = "ok" or "error" after the closing is complete.

      Parameters:
      args - exactly one: the path to a file of commands, one per line
      l - logger to receive events and output
    • runLookup

      private void runLookup(String[] args, Logging l)
      Perform a lookup of the name specified Deprecated - only used by CLI

      Event "lookupResult" = base64 of the destination, or an error message.

      Parameters:
      args - {name}
      l - logger to receive events and output
    • runPing

      private void runPing(String allargs, Logging l)
      Start up a ping task with the specified args (currently supporting -ns, -h, -l) Deprecated - only used by CLI

      Event "pingTaskId" = Integer of the taskId, or -1.

      Parameters:
      allargs - arguments to pass to the I2Ping task
      l - logger to receive events and output
    • runBlinding

      private void runBlinding(String[] argv)
      Send a BlindingInfo message, just for testing.
      Parameters:
      argv - the arguments after the "blinding" command word, parsed for the option letters d, p, k, s and e
    • closetask

      private boolean closetask(int num, I2PTunnel.CloseMode mode, Logging l)
      Helper method to actually close the given task number (optionally forcing closure).
      Parameters:
      num - the task id to look for, the search stops at a higher id
      mode - how to close it: normal, forced, or destroy
      l - unused, the class logger is used instead
      Returns:
      true if a task with that id was found and closed
    • closetask

      private boolean closetask(I2PTunnelTask t, I2PTunnel.CloseMode mode)
      Helper method to actually close the given task (optionally forcing closure).
      Parameters:
      t - the task to close
      mode - how to close it: normal, forced, or destroy
      Returns:
      true if the task reported it is closed
    • purgetasks

      private void purgetasks()
      Helper task to remove closed / completed tasks.
    • log

      public void log(String s)
      Log the given message using the logging subsystem and standard output.
      Specified by:
      log in interface Logging
      Parameters:
      s - message to log
    • makeKey

      private static void makeKey(OutputStream writeTo, OutputStream pubDest, Logging l)
      Create a new destination, storing the destination and its private keys where instructed. Does NOT support non-default sig types. Deprecated - only used by CLI.
      Parameters:
      writeTo - location to store the destination and private keys
      pubDest - location to store the destination
      l - logger to send messages to
    • showKey

      private static void showKey(InputStream readFrom, OutputStream pubDest, Logging l)
      Read in the given destination, display it, and write it to the given location Deprecated - only used by CLI.
      Parameters:
      readFrom - stream to read the destination from
      pubDest - stream to write the destination to
      l - logger to send messages to
    • writePubKey

      private static void writePubKey(Destination d, OutputStream o, Logging l) throws I2PException, IOException
      Write out the destination to the stream Deprecated - only used by CLI.
      Parameters:
      d - Destination to write
      o - stream to write the destination to, or null for noop
      l - logger to send messages to
      Throws:
      I2PException - if the destination's key cannot be encoded, a DataFormatException
      IOException - if the stream write fails
    • destFromName

      private static Destination destFromName(String name, String i2cpHost, String i2cpPort, boolean isSSL, String user, String pw) throws DataFormatException
      Resolve a destination from a name or Base64 string.
      Parameters:
      name - the destination as a local name, a base32 or base64 string, or a "file:" path
      i2cpHost - may be null
      i2cpPort - may be null
      isSSL - true to reach the router's I2CP proxy over TLS instead of plain TCP
      user - may be null
      pw - may be null
      Returns:
      the destination, or null if the name is unknown, the file cannot be read, or the lookup fails
      Throws:
      DataFormatException - if name is null or blank
    • addConnectionEventListener

      public void addConnectionEventListener(I2PTunnel.ConnectionEventListener lsnr)
      Registers a listener for connection events.

      The listener will be notified of router disconnection events.

      Parameters:
      lsnr - the listener to add; ignored if null
    • removeConnectionEventListener

      public void removeConnectionEventListener(I2PTunnel.ConnectionEventListener lsnr)
      Unregisters a connection event listener.
      Parameters:
      lsnr - the listener to remove; ignored if null
    • getPrefix

      private String getPrefix()
      Returns the log prefix naming the tunnel.
      Returns:
      the prefix with the tunnel id
    • getContext

      public I2PAppContext getContext()
      Gets the application context.
      Returns:
      the I2P application context
    • routerDisconnected

      void routerDisconnected()
      Called when the router disconnects unexpectedly.

      This method notifies all registered ConnectionEventListeners that the router connection has been lost.