- All Implemented Interfaces:
I2PSession, I2CPMessageReader.I2CPMessageEventListener
- Direct Known Subclasses:
I2PSessionImpl2
Public only for clearCache(). Except for methods defined in I2PSession and I2CPMessageEventListener, not maintained as a public API, not for external use. Use I2PClientFactory to get an I2PClient and then createSession().
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected classThis notifies the client of payload messages.private classTimeout for async lookup, if the router does not respond.private static classSimple object to wait for lookup replies.protected static enumSession state enumeration.private classCheck for unclaimed messages, without wastefully setting a timer for each message.Nested classes/interfaces inherited from interface I2PSession
I2PSession.TunnelPairModifier and TypeInterfaceDescriptionstatic classSimple holder for tunnel pair information.Field Summary
Modifier and TypeFieldDescriptionprotected I2PSessionImpl.AvailabilityNotifierThread that we tell when new messages are available, who then tells us to fetch them.protected Map<Long, MessagePayloadMessage> Map of Long--> MessagePayloadMessage.protected int[]Current bandwidth limits.protected final ObjectLock for bandwidth limit updates.protected final I2PAppContextApp context, kept separate so we can get rid of singletons.private ThrowableWhy the session failed, if it did.private StringThe message describing the last session error.private final booleanWhether fast receive was requested.protected final I2PClientMessageHandlerMapHandler map for I2CP message types.protected final StringHostname of router - will be null if in RouterContext.private booleanWhether the session is in reduced functionality mode.private AtomicLongWhen the session last sent or received.private AtomicLongWhen the lease set was last signed for LS2.protected LeaseSetCurrently granted lease set, or null.protected final ObjectMonitor for waiting until a lease set has been granted.protected final LogLogger for this session.private static final Map<Object, Destination> Cache of Destination lookups, keyed by a Hash or a String.private final AtomicIntegerCounter handing out lookup ids.private final DestinationOur destination.private longWhen the offline lease set expires.private SignatureSignature for the offline lease set.private final PropertiesConfiguration options.protected final LinkedBlockingQueue<I2PSessionImpl.LookupWaiter> Hashes of lookups we are waiting for.protected final intPort number of router - will be 0 if in RouterContext.private PrivateKeyPrivate key for decryption.protected final I2CPMessageProducerClass that generates new messages.protected I2CPMessageQueueUsed for internal connections to the router.protected I2CPMessageReaderReader that always searches for messages.private booleanWhether the router returns blinding info.private booleanWhether the router supports fast receive.private booleanWhether the router supports host lookups.private booleanWhether the router supports LS2.private booleanWhether the router supports subsessions.private StringThe router's version string.private SessionIdThis session's ID.protected I2PSessionListenerWhere session events are sent.private StringShort hash of the local destination.private SigningPrivateKeyPrivate key for signing.protected SocketSocket for communication.protected I2PSessionImpl.StateCurrent session state.protected final ObjectLock for state transitions.private final ObjectLock guarding the subsession lists.private final ConcurrentHashMap<SessionId, SubSession> The established subsessions by id.private final List<SubSession> The registered subsessions.protected SigningPublicKeyTransient signing public key for offline signatures.protected final Set<TunnelStatusListener> Listeners for tunnel status changes (tunnel failures and removals).protected ClientWriterRunnerWriter message queue.private static final intThe first reconnect try waits 10 seconds.private static final intReceive buffer size.protected static final intMaximum size of the lookup cache.(package private) static final SessionIdDummy session ID for messages before a real session is established.static final intDefault I2CP listen port.private static final LookupResultCached failure result for lookups.private static final intThe wait between reconnect tries tops out at 320 seconds.private static final longThe wait for send capacity is at most 10 seconds.private static final StringRouter version that first returned blinding info.private static final StringRouter version that first supported fast receive.private static final StringRouter version that first supported host lookups.private static final StringRouter version that first supported LS2.private static final StringRouter version that first supported subsessions.protected static final StringUse Unix domain socket (or similar) to connect to a router.private static final Set<I2PSessionImpl.State> States counted as closed.private static final Set<I2PSessionImpl.State> States counted as closed or closing.private static final Set<I2PSessionImpl.State> States counted as closed or opening.private static final Set<I2PSessionImpl.State> States counted as opening.private static final longUsage quota checks run every 1 minute.Fields inherited from interface I2PSession
PORT_ANY, PORT_UNSPECIFIED, PROTO_ANY, PROTO_DATAGRAM, PROTO_DATAGRAM_RAW, PROTO_DATAGRAM2, PROTO_DATAGRAM3, PROTO_STREAMING, PROTO_UNSPECIFIEDModifier and TypeFieldDescriptionstatic final intAny port.static final intUnspecified port.static final intAny protocol.static final intA repliable and signed datagram.static final intA raw (unsigned, unrepliable) datagram.static final intA repliable and signed datagram.static final intA repliable but unsigned datagram.static final intStreaming protocol.static final intUnspecified protocol.Constructor Summary
ModifierConstructorDescriptionprotectedI2PSessionImpl(I2PSessionImpl primary, InputStream destKeyStream, Properties options) For extension by SubSession viaI2PSessionMuxedImpland I2PSessionImpl2.I2PSessionImpl(I2PAppContext context, InputStream destKeyStream, Properties options) Create a new session, reading the Destination, PrivateKey, and SigningPrivateKey from the destKeyStream, and using the specified options to connect to the routerprotectedI2PSessionImpl(I2PAppContext context, Properties options, I2PClientMessageHandlerMap handlerMap) For extension by SimpleSession (no dest).privateI2PSessionImpl(I2PAppContext context, Properties options, I2PClientMessageHandlerMap handlerMap, I2CPMessageProducer producer, boolean hasDest) Basic setup of the session's final fields.Method Summary
Modifier and TypeMethodDescriptionvoidReceive a payload message and let the app know its available.addSubsession(InputStream privateKeyStream, Properties opts) Router must be connected or was connected...int[]Blocking.(package private) voidbwReceived(int[] limits) Called by the message handler.protected voidchangeState(I2PSessionImpl.State state) Change the session state.static voidClear the lookup cache.private voidClear out all pending lookups and bw limit requests.private voidClose the socket carefully.voidconnect()Connect to the router and establish a session.(package private) voiddateUpdated(String routerVersion) Update the router version and related feature support flags.(package private) voiddestLookupFailed(long nonce, int code) Called by the message handler on reception of HostReplyMessage.(package private) voidCalled by the message handler on reception of DestReplyMessage.(package private) voiddestReceived(long nonce, Destination d) Called by the message handler on reception of HostReplyMessage.(package private) voidCalled by the message handler on reception of DestReplyMessage.voidTear down the session, and do NOT reconnect.voiddestroySession(boolean sendDisconnect) Tear down the session, and do NOT reconnect.voiddiscardMessage(int msgId) Throw away the received message, we don't want it.protected voidWill interrupt a connect in progress.voiddisconnected(I2CPMessageReader reader) The I2CPMessageEventListener callback.private Propertiesfilter(Properties options) Save some memory, don't pass along the pointless properties.(package private) I2PAppContextFor Subsessions.booleanDoes this session support fast receive?(package private) I2PClientMessageHandlerMapFor Subsessions.private StringgetHost()I2CP host from the config.(package private) longThe published timestamp of the last LS2 we signed.Current lease set published by this session.Retrieve the destination of the session.protected StringgetName()Session name for logging.private voidgetName(StringBuilder buf) Append the session name for log messages.longJava time (ms) or 0 if not initialized or does not have offline keys.Null on error or if not initialized or does not have offline keys.Retrieve the configuration options, filtered.private intgetPort()I2CP port from the config.protected final StringTry hard to make a decent identifier as this will appear in error logs.Retrieve the signing SigningPrivateKey.(package private) I2CPMessageProducerRetrieve the helper that generates I2CP messages.Always valid in RouterContext.(package private) SessionIdRetrieve the session's ID.List of subsessions, non-null, does not include the primary session.Null on error or if not initialized or does not have offline keys.private intMinutes to wait for the first lease set during connect, from the session options if set there, else from the router options, else the 1 hour default.(package private) static intgetTunnelBuildTimeout(String sessionValue, String contextValue) Parse the tunnel build timeout, shared with the instance method and tests.private booleanCheck if a streaming property should be allowed through the filter.booleanisClosed()Has the session been closed (or not yet connected)? False when open and during transitions.booleanDoes this session have offline and transient keys?longTime of last session activity in milliseconds.private final PropertiesloadConfig(Properties opts) Parse the config for anything we know about.private voidClose the socket carefully.lookupDest(String name) Ask the router to lookup a Destination by host name.lookupDest(String name, long maxWait) Ask the router to lookup a Destination by host name.lookupDest(String name, long maxWait, LookupCallback callback) Lookup a Destination by hash.lookupDest(Hash h) Blocking.lookupDest(Hash h, long maxWait) Blocking.lookupDest(Hash h, long maxWait, LookupCallback callback) Lookup a Destination by hostname.lookupDest2(String name, long maxWait) Ask the router to lookup a Destination by host name.voidmessageReceived(I2CPMessageReader reader, I2CPMessage message) The I2CPMessageEventListener callback.(package private) voidpropagateError(String msg, Throwable error) Pass off the error to the listener Misspelled, oh well.private voidreadDestination(InputStream destKeyStream) Load up the destKeyFile for our Destination, PrivateKey, and SigningPrivateKey.voidreadError(I2CPMessageReader reader, Exception error) The I2CPMessageEventListener callback.byte[]receiveMessage(int msgId) Pull the unencrypted data from the message that we've already prefetched and notified the user that its available.abstract voidreceiveStatus(int msgId, long nonce, int status) Receive a message status update.protected booleanAttempt to reconnect to the router.voidremoveSubsession(I2PSession session) No-op, this session has no subsessions.voidreportAbuse(int msgId, int severity) Report abuse with regards to the given messageId.voidSend blinding info to a peer.(package private) voidsendMessage(I2CPMessage message) Deliver an I2CP message to the router As of 0.9.3, may block for several seconds if the write queue to the router is full.(package private) voidsendMessage_unchecked(I2CPMessage message) Deliver an I2CP message to the router.(package private) voidsetLastLS2SignTime(long now) The published timestamp of the last LS2 we signed.(package private) voidsetLeaseSet(LeaseSet ls) Lease set published by this session.voidMark the session as reduced.(package private) voidSession ID assigned by the router.voidConfigure the listener.protected booleanWhether the session should attempt reconnection on disconnect.private voidStarts the thread that closes idle sessions.protected voidFire up a periodic task to check for unclaimed messages.booleanDoes this session support LS2?toString()protected voidUpdate the last activity timestamp.voidupdateOptions(Properties options) Update the tunnel and bandwidth settings.protected voidThrows I2PSessionException if uninitialized, closed or closing.protected voidWait for a SetDate response from the router.private I2PSessionImpl.LookupWaiterx_lookupDest(String name, long maxWait) Ask the router to lookup a Destination by host name.Methods inherited from class Object
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface I2PSession
addMuxedSessionListener, addSessionListener, addTunnelStatusListener, getCurrentTunnelPair, getDecryptionKey, rebuildTunnels, removeListener, removeTunnelStatusListener, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, sendMessage, setCurrentTunnelPair, switchToNewTunnelModifier and TypeMethodDescriptionvoidaddMuxedSessionListener(I2PSessionMuxedListener l, int proto, int port) Listen on specified protocol and port, and receive notification of proto, fromPort, and toPort for every message.voidaddSessionListener(I2PSessionListener lsnr, int proto, int port) Listen on specified protocol and port.voidAdd a listener for tunnel status changes.Get the tunnel IDs currently in use by this session.Retrieve the decryption PrivateKey associated with the Destination.voidForce immediate tunnel rebuild.voidremoveListener(int proto, int port) Removes the specified listener (only).voidRemove a tunnel status listener.booleansendMessage(Destination dest, byte[] payload) Send a new message to the given destination, containing the specified payload, returning true if the router feels confident that the message was delivered.booleansendMessage(Destination dest, byte[] payload, int offset, int size) Send a new message to the given destination, containing the specified payload, returning true if the router feels confident that the message was delivered.booleansendMessage(Destination dest, byte[] payload, int proto, int fromport, int toport) See I2PSessionMuxedImpl for proto/port details.booleansendMessage(Destination dest, byte[] payload, int offset, int size, int proto, int fromPort, int toPort, SendMessageOptions options) See I2PSessionMuxedImpl for proto/port details.longsendMessage(Destination dest, byte[] payload, int offset, int size, int proto, int fromPort, int toPort, SendMessageOptions options, SendMessageStatusListener listener) Send a message and request an asynchronous notification of delivery status.booleansendMessage(Destination dest, byte[] payload, int offset, int size, SessionKey keyUsed, Set<SessionTag> tagsSent) End-to-End Crypto is disabled, tags and keys are ignored.booleansendMessage(Destination dest, byte[] payload, int offset, int size, SessionKey keyUsed, Set<SessionTag> tagsSent, int proto, int fromPort, int toPort) See I2PSessionMuxedImpl for proto/port details.booleansendMessage(Destination dest, byte[] payload, int offset, int size, SessionKey keyUsed, Set<SessionTag> tagsSent, long expire) End-to-End Crypto is disabled, tags and keys are ignored.booleansendMessage(Destination dest, byte[] payload, int offset, int size, SessionKey keyUsed, Set<SessionTag> tagsSent, long expire, int proto, int fromPort, int toPort) See I2PSessionMuxedImpl for proto/port details.booleansendMessage(Destination dest, byte[] payload, int offset, int size, SessionKey keyUsed, Set<SessionTag> tagsSent, long expire, int proto, int fromPort, int toPort, int flags) See I2PSessionMuxedImpl for proto/port details.booleansendMessage(Destination dest, byte[] payload, SessionKey keyUsed, Set<SessionTag> tagsSent) End-to-End Crypto is disabled, tags and keys are ignored!voidTunnel IDs actively in use by this session.booleanSwitch to a new tunnel for this session.
Field Details
_log
Logger for this session._myDestination
Our destination._privateKey
Private key for decryption._signingPrivateKey
Private key for signing._options
Configuration options._sessionId
This session's ID._leaseSet
Currently granted lease set, or null._offlineExpiration
private long _offlineExpirationWhen the offline lease set expires._offlineSignature
Signature for the offline lease set._transientSigningPublicKey
Transient signing public key for offline signatures._lastLS2SignTime
When the lease set was last signed for LS2._subsessions
The registered subsessions._subsessionMap
The established subsessions by id._subsessionLock
Lock guarding the subsession lists.MIN_SUBSESSION_VERSION
Router version that first supported subsessions.- See Also:
_routerSupportsSubsessions
private volatile boolean _routerSupportsSubsessionsWhether the router supports subsessions._hostname
Hostname of router - will be null if in RouterContext._portNum
protected final int _portNumPort number of router - will be 0 if in RouterContext._socket
Socket for communication._reader
Reader that always searches for messages._writer
Writer message queue._queue
Used for internal connections to the router. If this is set, _socket and _writer will be null._sessionListener
Where session events are sent._producer
Class that generates new messages._availableMessages
Map of Long--> MessagePayloadMessage._pendingLookups
Hashes of lookups we are waiting for._lookupID
Counter handing out lookup ids._bwReceivedLock
Lock for bandwidth limit updates._bwLimits
protected volatile int[] _bwLimitsCurrent bandwidth limits._routerVersion
The router's version string._shortHash
Short hash of the local destination._handlerMap
Handler map for I2CP message types._context
App context, kept separate so we can get rid of singletons._leaseSetWait
Monitor for waiting until a lease set has been granted._errorMessage
The message describing the last session error._errorCause
Why the session failed, if it did.STATES_CLOSED
States counted as closed.STATES_OPENING
States counted as opening.STATES_CLOSED_OR_OPENING
States counted as closed or opening.STATES_CLOSED_OR_CLOSING
States counted as closed or closing._state
Current session state._stateLock
Lock for state transitions._availabilityNotifier
Thread that we tell when new messages are available, who then tells us to fetch them. The point of this is so that the fetch doesn't block the reading of other messages (in turn, potentially leading to deadlock)._lastActivity
When the session last sent or received._isReduced
private volatile boolean _isReducedWhether the session is in reduced functionality mode._fastReceive
private final boolean _fastReceiveWhether fast receive was requested._routerSupportsFastReceive
private volatile boolean _routerSupportsFastReceiveWhether the router supports fast receive._routerSupportsHostLookup
private volatile boolean _routerSupportsHostLookupWhether the router supports host lookups._routerSupportsLS2
private volatile boolean _routerSupportsLS2Whether the router supports LS2._routerSupportsBlindingInfo
private volatile boolean _routerSupportsBlindingInfoWhether the router returns blinding info._tunnelStatusListeners
Listeners for tunnel status changes (tunnel failures and removals).CACHE_MAX_SIZE
protected static final int CACHE_MAX_SIZEMaximum size of the lookup cache._lookupCache
Cache of Destination lookups, keyed by a Hash or a String.Since 0.9.11 the key may be a String as well as a Hash.
MIN_HOST_LOOKUP_VERSION
Router version that first supported host lookups.- See Also:
LOOKUP_FAILURE
Cached failure result for lookups.PROP_DOMAIN_SOCKET
Use Unix domain socket (or similar) to connect to a router.- See Also:
VERIFY_USAGE_TIME
private static final long VERIFY_USAGE_TIMEUsage quota checks run every 1 minute.- See Also:
MAX_SEND_WAIT
private static final long MAX_SEND_WAITThe wait for send capacity is at most 10 seconds.- See Also:
MIN_FAST_VERSION
Router version that first supported fast receive.- See Also:
MIN_LS2_VERSION
Router version that first supported LS2.- See Also:
MIN_BLINDINFO_VERSION
Router version that first returned blinding info.- See Also:
LISTEN_PORT
BUF_SIZE
private static final int BUF_SIZEReceive buffer size.DUMMY_SESSION
Dummy session ID for messages before a real session is established.MAX_RECONNECT_DELAY
private static final int MAX_RECONNECT_DELAYThe wait between reconnect tries tops out at 320 seconds.- See Also:
BASE_RECONNECT_DELAY
private static final int BASE_RECONNECT_DELAYThe first reconnect try waits 10 seconds.- See Also:
Constructor Details
I2PSessionImpl
protected I2PSessionImpl(I2PAppContext context, Properties options, I2PClientMessageHandlerMap handlerMap) For extension by SimpleSession (no dest).- Parameters:
context- the I2P app contextoptions- session configuration optionshandlerMap- the I2CP message handler map
I2PSessionImpl
protected I2PSessionImpl(I2PSessionImpl primary, InputStream destKeyStream, Properties options) throws I2PSessionException For extension by SubSession viaI2PSessionMuxedImpland I2PSessionImpl2.- Parameters:
primary- the muxed session sharing this session's context, handlers and producerdestKeyStream- stream containing the private key data, format is specified inPrivateKeyFileoptions- set of options to configure the router with, if null will use System properties- Throws:
I2PSessionException- if the destination key stream cannot be read or is not in the expected format
I2PSessionImpl
private I2PSessionImpl(I2PAppContext context, Properties options, I2PClientMessageHandlerMap handlerMap, I2CPMessageProducer producer, boolean hasDest) Basic setup of the session's final fields.- Parameters:
context- the app contextoptions- the session optionshandlerMap- the map of the message handlersproducer- the I2CP message producerhasDest- true if a destination was supplied
I2PSessionImpl
public I2PSessionImpl(I2PAppContext context, InputStream destKeyStream, Properties options) throws I2PSessionException Create a new session, reading the Destination, PrivateKey, and SigningPrivateKey from the destKeyStream, and using the specified options to connect to the routerAs of 0.9.19, defaults in options are honored.
This does NOT validate consistency of the destKeyStream, e.g. pubkey/privkey match or valid offline sig. The router does that.
- Parameters:
context- the I2P app contextdestKeyStream- stream containing the private key data, format is specified inPrivateKeyFileoptions- set of options to configure the router with, if null will use System properties- Throws:
I2PSessionException- if there is a problem loading the private keys
Method Details
dateUpdated
Update the router version and related feature support flags.- Parameters:
routerVersion- as rcvd in the SetDateMessage, may be null for very old routers
addSubsession
public I2PSession addSubsession(InputStream privateKeyStream, Properties opts) throws I2PSessionException Router must be connected or was connected... for now.- Specified by:
addSubsessionin interfaceI2PSession- Parameters:
privateKeyStream- null for transient, if non-null must have same encryption keys as primary sessionopts- subsession options if any, may be null- Returns:
- a new subsession, non-null
- Throws:
I2PSessionException- if the router does not support sub-sessions, or a sub-session request is pending or the same key was already added
removeSubsession
No-op, this session has no subsessions.- Specified by:
removeSubsessionin interfaceI2PSession- Parameters:
session- the subsession to remove
getSubsessions
List of subsessions, non-null, does not include the primary session.- Specified by:
getSubsessionsin interfaceI2PSession- Returns:
- the subsessions, in registration order
loadConfig
Parse the config for anything we know about. Also fill in the authorization properties if missing.- Parameters:
opts- the caller-supplied session options, copied and augmented- Returns:
- the configuration properties
getTunnelBuildTimeout
private int getTunnelBuildTimeout()Minutes to wait for the first lease set during connect, from the session options if set there, else from the router options, else the 1 hour default.- Returns:
- minutes, at least 1
getTunnelBuildTimeout
Parse the tunnel build timeout, shared with the instance method and tests. Invalid or non-positive values fall back to the 1 hour default.- Parameters:
sessionValue- per-session option value, or nullcontextValue- router option value, or null- Returns:
- minutes, at least 1
getHost
I2CP host from the config.- Returns:
- configured host name, or a placeholder for logging if not applicable
getPort
private int getPort()I2CP port from the config.- Returns:
- configured port, 0 if not applicable, or
LISTEN_PORTif unparseable
filter
Save some memory, don't pass along the pointless properties. As of 0.9.19, defaults from options will be promoted to real values in rv.- Parameters:
options- the properties to filter, system and disallowed streaming keys are dropped- Returns:
- a new Properties without defaults
isAllowedStreamingProperty
Check if a streaming property should be allowed through the filter. These are known-good streaming options that should be passed to the router.- Parameters:
key- the property key- Returns:
- true if the property should be allowed
updateOptions
Update the tunnel and bandwidth settings.- Specified by:
updateOptionsin interfaceI2PSession- Parameters:
options- non-null
getFastReceive
public boolean getFastReceive()Does this session support fast receive?- Returns:
- true if fast receive is supported
supportsLS2
public boolean supportsLS2()Does this session support LS2?- Returns:
- true if LS2 is supported
setLeaseSet
Lease set published by this session.- Parameters:
ls- the lease set to publish, or null to withdraw the current one
getLeaseSet
Current lease set published by this session. Each lease in the lease set corresponds to one inbound tunnel allocated to this session by the router, so the lease count is the number of active inbound tunnels for this destination.- Returns:
- the current lease set, or null if not yet published
changeState
Change the session state.- Parameters:
state- the new state to move to, waking any waiter blocked on a state change
readDestination
Load up the destKeyFile for our Destination, PrivateKey, and SigningPrivateKey. As of 0.9.38, loads the offline data also. See PrivateKeyFile.This does NOT validate consistency of the destKeyStream, e.g. pubkey/privkey match or valid offline sig. The router does that.
- Parameters:
destKeyStream- the stream to read the Destination, PrivateKey and SigningPrivateKey from- Throws:
DataFormatException- if the file is in the wrong format or keys are invalidIOException- if there is a problem reading the file
isOffline
public boolean isOffline()Does this session have offline and transient keys?- Specified by:
isOfflinein interfaceI2PSession- Returns:
- true if the session was created from an offline-signed destination
getOfflineExpiration
public long getOfflineExpiration()Java time (ms) or 0 if not initialized or does not have offline keys.- Specified by:
getOfflineExpirationin interfaceI2PSession- Returns:
- the expiry time, or 0 when unavailable
getOfflineSignature
Null on error or if not initialized or does not have offline keys.- Specified by:
getOfflineSignaturein interfaceI2PSession- Returns:
- the signature, or null when unavailable
getTransientSigningPublicKey
Null on error or if not initialized or does not have offline keys.- Specified by:
getTransientSigningPublicKeyin interfaceI2PSession- Returns:
- the signature, or null when unavailable
connect
Connect to the router and establish a session. This call blocks until a session is granted.Should be threadsafe, other threads will block until complete. Disconnect / destroy from another thread may be called simultaneously and will (should?) interrupt the connect.
Connecting a primary session will not automatically connect subsessions. Connecting a subsession will automatically connect the primary session if not previously connected.
- Specified by:
connectin interfaceI2PSession- Throws:
I2PSessionException- if there is a configuration error or the router is not reachable
waitForDate
Wait for a SetDate response from the router.- Throws:
InterruptedException- if the calling thread is interrupted while waitingIOException- on I/O error
receiveMessage
Pull the unencrypted data from the message that we've already prefetched and notified the user that its available.- Specified by:
receiveMessagein interfaceI2PSession- Parameters:
msgId- message to fetch- Returns:
- the data, or null on error
- Throws:
I2PSessionException- declared but never thrown; failures return null instead
discardMessage
public void discardMessage(int msgId) Throw away the received message, we don't want it. Use instead ofreceiveMessage(int)to avoid gunzip overhead.- Specified by:
discardMessagein interfaceI2PSession- Parameters:
msgId- message whose payload should be dropped rather than returned
reportAbuse
Report abuse with regards to the given messageId.- Specified by:
reportAbusein interfaceI2PSession- Parameters:
msgId- message that was abusive (or -1 for not message related)severity- abuse rating from 1 (mildest) to 100 (worst)- Throws:
I2PSessionException- if the session is not open or closed
receiveStatus
public abstract void receiveStatus(int msgId, long nonce, int status) Receive a message status update.- Parameters:
msgId- the message IDnonce- router-assigned value identifying the request the update belongs tostatus- the MessageStatusMessage.STATUS_ code for the send outcome
addNewMessage
Receive a payload message and let the app know its available.- Parameters:
msg- the payload message
startVerifyUsage
protected void startVerifyUsage()Fire up a periodic task to check for unclaimed messages.messageReceived
The I2CPMessageEventListener callback. Receive notification of some I2CP message and handle it if possible.We route the message based on message type AND session ID.
The following types never contain a session ID and are not routable to a subsession: BandwidthLimitsMessage, DestReplyMessage
The following types may not contain a valid session ID even when intended for a subsession, so we must take special care: SessionStatusMessage.
- Specified by:
messageReceivedin interfaceI2CPMessageReader.I2CPMessageEventListener- Parameters:
reader- ignored, the session already holds its own connectionmessage- the I2CPMessage
readError
The I2CPMessageEventListener callback. Receive notification of an error reading the I2CP stream. As of 0.9.41, does NOT call sessionlistener.disconnected(I2CPMessageReader), the I2CPMessageReader will call disconnected() also.- Specified by:
readErrorin interfaceI2CPMessageReader.I2CPMessageEventListener- Parameters:
reader- ignored, only the error is usederror- non-null
getMyDestination
Retrieve the destination of the session.- Specified by:
getMyDestinationin interfaceI2PSession- Returns:
- the my destination
getPrivateKey
Retrieve the signing SigningPrivateKey. As of 0.9.38, this will be the transient key if offline signed.- Specified by:
getPrivateKeyin interfaceI2PSession- Returns:
- the private key
getProducer
I2CPMessageProducer getProducer()Retrieve the helper that generates I2CP messages.- Returns:
- the I2CP message producer
getHandlerMap
getContext
getOptions
Retrieve the configuration options, filtered. All defaults passed in via constructor have been promoted to the primary map. Reflects updates applied viaupdateOptions(Properties), including router-side reconfiguration, so the effective tunnel quantity settings for this session may be read from the returned properties.- Returns:
- non-null, if instantiated with null options, this will be the System properties.
getSessionId
setSessionId
Session ID assigned by the router.- Parameters:
id- the session ID to set
getLastLS2SignTime
long getLastLS2SignTime()The published timestamp of the last LS2 we signed.- Returns:
- 0 if never
setLastLS2SignTime
void setLastLS2SignTime(long now) The published timestamp of the last LS2 we signed.- Parameters:
now- the timestamp to set
setSessionListener
Configure the listener.- Specified by:
setSessionListenerin interfaceI2PSession- Parameters:
lsnr- listener to retrieve events
isClosed
public boolean isClosed()Has the session been closed (or not yet connected)? False when open and during transitions. Synchronized.- Specified by:
isClosedin interfaceI2PSession- Returns:
- true if the session is closed or not yet connected
verifyOpen
Throws I2PSessionException if uninitialized, closed or closing. Blocks if opening.- Throws:
I2PSessionException- if not open
sendMessage
Deliver an I2CP message to the router As of 0.9.3, may block for several seconds if the write queue to the router is full.- Parameters:
message- the I2CP message to send- Throws:
I2PSessionException- if the message is malformed or there is an error writing it out
sendMessage_unchecked
Deliver an I2CP message to the router. Does NOT check state. Call only from connect() or other methods that need to send messages when not in OPEN state.- Parameters:
message- the I2CP message to send- Throws:
I2PSessionException- if the message is malformed or there is an error writing it out
propagateError
destroySession
public void destroySession()Tear down the session, and do NOT reconnect.Blocks if session has not been fully started.
- Specified by:
destroySessionin interfaceI2PSession
destroySession
public void destroySession(boolean sendDisconnect) Tear down the session, and do NOT reconnect.Will interrupt an open in progress. Calls sessionlistener.disconnected().
- Parameters:
sendDisconnect- if true, send disconnect message to router
closeSocket
private void closeSocket()Close the socket carefully.locked_closeSocket
private void locked_closeSocket()Close the socket carefully. Caller must change state.disconnected
The I2CPMessageEventListener callback. Receive notification that the I2CP connection was disconnected. Calls sessionlistener.disconnected().- Specified by:
disconnectedin interfaceI2CPMessageReader.I2CPMessageEventListener- Parameters:
reader- ignored, the session tracks its own connection
disconnect
protected void disconnect()Will interrupt a connect in progress. Calls sessionlistener.disconnected().shouldReconnect
protected boolean shouldReconnect()Whether the session should attempt reconnection on disconnect.- Returns:
- true if the session should attempt to reconnect
reconnect
protected boolean reconnect()Attempt to reconnect to the router.- Returns:
- true if reconnected successfully
getPrefix
Try hard to make a decent identifier as this will appear in error logs.- Returns:
- the prefix string
getName
getName
Append the session name for log messages.- Parameters:
buf- the buffer the nickname, or the class name if none is set, is appended to
destReceived
Called by the message handler on reception of DestReplyMessage.- Parameters:
d- non-null
destLookupFailed
Called by the message handler on reception of DestReplyMessage.- Parameters:
h- non-null
clearPendingLookups
private void clearPendingLookups()Clear out all pending lookups and bw limit requests.destReceived
Called by the message handler on reception of HostReplyMessage.- Parameters:
nonce- the lookup nonced- non-null
destLookupFailed
void destLookupFailed(long nonce, int code) Called by the message handler on reception of HostReplyMessage.- Parameters:
nonce- the lookup noncecode- the failure code
bwReceived
void bwReceived(int[] limits) Called by the message handler.- Parameters:
limits- the bandwidth limits
clearCache
public static void clearCache()Clear the lookup cache.lookupDest
Blocking. Waits a max of 10 seconds by default. See lookupDest with maxWait parameter to change. Implemented in 0.8.3 in I2PSessionImpl; previously was available only inI2PSimpleSession. Multiple outstanding lookups are now allowed.- Specified by:
lookupDestin interfaceI2PSession- Parameters:
h- the hash to look up- Returns:
- null on failure
- Throws:
I2PSessionException- if the calling thread is interrupted while waiting
lookupDest
Blocking. Waits a max of 10 seconds by default.- Specified by:
lookupDestin interfaceI2PSession- Parameters:
h- the hash to look upmaxWait- milliseconds to wait for the router's reply before giving up- Returns:
- null on failure
- Throws:
I2PSessionException- if the calling thread is interrupted while waiting
lookupDest
Ask the router to lookup a Destination by host name. Blocking. Waits a max of 10 seconds by default.This only makes sense for a b32 hostname, OR outside router context. Inside router context, just query the naming service. Outside router context, this does NOT query the context naming service. Do that first if you expect a local addressbook.
This will log a warning for non-b32 in router context.
See interface for suggested implementation.
Requires router side to be 0.9.11 or higher. If the router is older, this will return null immediately.
- Specified by:
lookupDestin interfaceI2PSession- Parameters:
name- the hostname to look up- Returns:
- the Destination, or null on failure
- Throws:
I2PSessionException- if the calling thread is interrupted while waiting
lookupDest
Ask the router to lookup a Destination by host name. Blocking. See above for details.- Specified by:
lookupDestin interfaceI2PSession- Parameters:
name- the hostname to look upmaxWait- milliseconds to wait for the router's reply before giving up- Returns:
- null on failure
- Throws:
I2PSessionException- if the calling thread is interrupted while waiting
lookupDest2
Ask the router to lookup a Destination by host name. Blocking. See above for details. Same aslookupDest(Hash)but with a failure code in the return value.- Specified by:
lookupDest2in interfaceI2PSession- Parameters:
name- the hostname to look upmaxWait- milliseconds to wait for the router's reply before giving up- Returns:
- non-null
- Throws:
I2PSessionException- if the calling thread is interrupted while waiting
x_lookupDest
private I2PSessionImpl.LookupWaiter x_lookupDest(String name, long maxWait) throws I2PSessionException Ask the router to lookup a Destination by host name. Blocking. See above for details.- Parameters:
name- the hostname to look upmaxWait- milliseconds to wait for the router's reply before giving up- Returns:
- null on failure
- Throws:
I2PSessionException- if the thread is interrupted while waiting for the router's reply
lookupDest
public LookupResult lookupDest(Hash h, long maxWait, LookupCallback callback) throws I2PSessionException Lookup a Destination by hostname. Non-blocking. If the result is cached or there is an immediate failure, the result code will be something other than RESULT_DEFERRED, and the callback will NOT be called.- Specified by:
lookupDestin interfaceI2PSession- Parameters:
h- the hash to look upmaxWait- milliseconds to wait for the router's reply before giving upcallback- to return the result, non-null- Returns:
- non-null. If result code is RESULT_DEFERRED, callback will be called later
- Throws:
I2PSessionException- if the router predates 0.9.11 and has no HostLookup
lookupDest
public LookupResult lookupDest(String name, long maxWait, LookupCallback callback) throws I2PSessionException Lookup a Destination by hash. Non-blocking. If the result is cached or there is an immediate failure, the result code will be something other than RESULT_DEFERRED, and the callback will NOT be called.- Specified by:
lookupDestin interfaceI2PSession- Parameters:
name- the hostname to look upmaxWait- milliseconds to wait for the router's reply before giving upcallback- to return the result, non-null- Returns:
- non-null. If result code is RESULT_DEFERRED, callback will be called later
- Throws:
I2PSessionException- if the router predates 0.9.11 and has no HostLookup
bandwidthLimits
Blocking. Waits a max of 5 seconds. But shouldn't take long. Implemented in 0.8.3 in I2PSessionImpl; previously was available only in I2PSimpleSession. Multiple outstanding lookups are now allowed.- Specified by:
bandwidthLimitsin interfaceI2PSession- Returns:
- null on failure
- Throws:
I2PSessionException- if the calling thread is interrupted while waiting
sendBlindingInfo
Send blinding info to a peer.- Specified by:
sendBlindingInfoin interfaceI2PSession- Parameters:
bd- the blind data- Throws:
I2PSessionException- if the router predates 0.9.43 and has no BlindingInfo
getRouterVersion
Always valid in RouterContext. Returns null if not yet connected inI2PAppContext.- Specified by:
getRouterVersionin interfaceI2PSession- Returns:
- null if unknown
updateActivity
protected void updateActivity()Update the last activity timestamp.lastActivity
public long lastActivity()Time of last session activity in milliseconds.- Returns:
- the last activity timestamp
setReduced
public void setReduced()Mark the session as reduced.startIdleMonitor
private void startIdleMonitor()Starts the thread that closes idle sessions.toString