java.lang.Object
net.i2p.client.streaming.impl.PacketHandler
Handles incoming packets by dispatching them to the appropriate connection, server socket, or responding with a reset (RST) packet if no valid connection is found.
Packet flow: I2PSession -> MessageHandler -> PacketHandler -> ConnectionPacketHandler -> MessageInputStream.
Field Summary
FieldsModifier and TypeFieldDescriptionprivate PacketDispatcherSharded dispatcher for known-connection packets, created lazily on the first inbound packet and shut down with the manager.private final ByteCachePooled buffers for incoming packets.private final I2PAppContextThe context the handler runs in.private static final ThreadLocal<SimpleDateFormat> Formatter for the date in packet options.private final LogLogger for this class.private final ConnectionManagerThe manager whose packets are handled.(package private) static final intUpper bound on inbound receive workers per manager.(package private) static final StringProperty limiting the number of inbound packet receive workers per connection manager.(package private) static final intPer-shard inbound queue capacity.Constructor Summary
ConstructorsConstructorDescriptionPacketHandler(I2PAppContext ctx, ConnectionManager mgr) Stores the context and manager, and opens the logger for the class.Method Summary
Modifier and TypeMethodDescriptionprivate voiddispatchKnownConnection(Connection con, Packet packet, long sendId) Offload (con, packet) to the shard owning the connection.(package private) voiddisplayPacket(Packet packet, String prefix, String suffix) Logs the provided packet at debug level with a timestamp.private PacketDispatcherLazily create the sharded dispatcher.private voidhandleEchoOnUnknown(Packet packet) Handles an echo packet received on an unknown connection.private voidhandleEchoPacket(Connection con, Packet packet) Handles echo packets on known connections.private voidhandleMisroutedPacket(Connection con, Packet packet) Handles a packet that appears on a known connection, but with stream ID mismatches or other anomalies.private static booleanisValidMatch(long conStreamId, long packetStreamId) Validates that the connection's stream ID matches the packet's stream ID and is non-zero.private voidreceiveKnownConnection(Connection con, Packet packet) Process a packet that matches a known connection.(package private) voidreceivePacket(Packet packet) Receives a packet and dispatches it to the appropriate handler.(package private) voidreceivePacketDirect(Packet packet, boolean queueIfNoConn) Processes the packet immediately, optionally queuing if no connection is found.private voidreceivePing(Connection con, Packet packet) Verifies and processes an incoming ping packet.private voidreceivePong(Packet packet) Processes an incoming pong packet.private voidreceiveUnknownConnection(Packet packet, long sendId, boolean queueIfNoConn) Processes a packet that does not match any known connection.private voidSends a reset packet back to the sender if the incoming packet is verified.voidsendResetUnverified(Packet packet) Sends a reset packet back to the sender without verifying the packet signature.(package private) voidShut down the receive workers, if any were created, releasing queued packets.(package private) static intworkerCountFor(int cores, String configured, int override) Clamped inbound receive worker count for a manager.
Field Details
manager
The manager whose packets are handled.context
The context the handler runs in.log
Logger for this class.cache
Pooled buffers for incoming packets.PROP_RECEIVE_WORKERS
Property limiting the number of inbound packet receive workers per connection manager. Unset or invalid values fall back to the platform core count.- See Also:
MAX_RECEIVE_WORKERS
static final int MAX_RECEIVE_WORKERSUpper bound on inbound receive workers per manager.- See Also:
RECEIVE_QUEUE_CAPACITY
static final int RECEIVE_QUEUE_CAPACITYPer-shard inbound queue capacity. A full queue back-pressures the session notifier thread rather than dropping or reordering packets.- See Also:
_dispatcher
Sharded dispatcher for known-connection packets, created lazily on the first inbound packet and shut down with the manager. Guarded by the volatile field + double-checked locking ingetDispatcher().DATE_FORMAT
Formatter for the date in packet options.
Constructor Details
PacketHandler
Stores the context and manager, and opens the logger for the class.- Parameters:
ctx- the app context used for logging, properties and packet verificationmgr- the connection manager whose connections dispatch inbound packets
Method Details
receivePacket
Receives a packet and dispatches it to the appropriate handler.- Parameters:
packet- the packet to process
receivePacketDirect
Processes the packet immediately, optionally queuing if no connection is found.- Parameters:
packet- the packet to processqueueIfNoConn- queue the packet if no matching connection exists
dispatchKnownConnection
Offload (con, packet) to the shard owning the connection. Per-connection FIFO ordering is preserved (a connection always maps to one worker) while packets for different connections run in parallel, so a slow connection or signature work no longer stalls the session notifier thread for all other connections on the same destination. If the shard's queue is full the notifier waits for space (the same blocking behaviour as processing the packet synchronously), so a packet is never dropped for want of queue space, and a connection always maps to the same shard, so it is never reordered.Two exits do drop a packet, both rare and both releasing the payload rather than leaking it: the interrupt handled below, and a worker-set resize - an entry handed to a worker between that worker idling out and being retired is freed when the retiring worker drains its queue. The peer recovers either way by retransmission.
- Parameters:
con- the connection, indexed by sendIdpacket- the packet; ownership passes to the receiving shardsendId- the connection's inbound stream id (shard key)
getDispatcher
Lazily create the sharded dispatcher. Worker count comes from the Tuner's global default (ConnectionOptions.getReceiveWorkerThreads()) when armed, elsePROP_RECEIVE_WORKERSwhen set, else the platform core count, all clamped toMAX_RECEIVE_WORKERS.- Returns:
- the shared dispatcher, never null
shutdownDispatcher
void shutdownDispatcher()Shut down the receive workers, if any were created, releasing queued packets. Called fromConnectionManager.shutdown(); idempotent.workerCountFor
Clamped inbound receive worker count for a manager.The Tuner's live default wins when positive, so runtime tuning applies to managers created after the adjustment; otherwise a positive configured property value wins (capped at
MAX_RECEIVE_WORKERS); otherwise the platform core count is used, floored at 2 for low-core hosts. Package-visible for unit tests.- Parameters:
cores- available processors at startupconfigured- raw property value, may be nulloverride- Tuner global default, 0 = not armed- Returns:
- the worker count, in 1..MAX_RECEIVE_WORKERS
displayPacket
receiveKnownConnection
Process a packet that matches a known connection.- Parameters:
con- the connection this packet belongs topacket- the incoming packet, matched to an established connection
handleEchoPacket
Handles echo packets on known connections.- Parameters:
con- the connection the ECHO packet arrived onpacket- the received ECHO packet
handleMisroutedPacket
Handles a packet that appears on a known connection, but with stream ID mismatches or other anomalies.- Parameters:
con- the connection the packet arrived onpacket- the misrouted packet to reclassify
sendReset
Sends a reset packet back to the sender if the incoming packet is verified.- Parameters:
packet- the received packet to answer, whose FROM option names the peer
sendResetUnverified
Sends a reset packet back to the sender without verifying the packet signature. Packet MUST have a FROM option.- Parameters:
packet- the received packet to answer; must carry a FROM option
receiveUnknownConnection
Processes a packet that does not match any known connection.- Parameters:
packet- the unmatched packetsendId- stream ID of the senderqueueIfNoConn- whether to queue the packet if connection is not found
handleEchoOnUnknown
Handles an echo packet received on an unknown connection.- Parameters:
packet- the echo packet
receivePing
Verifies and processes an incoming ping packet.- Parameters:
con- the connection from which ping originated, or null if unknownpacket- the ping packet
receivePong
Processes an incoming pong packet.- Parameters:
packet- the pong packet
isValidMatch
private static boolean isValidMatch(long conStreamId, long packetStreamId) Validates that the connection's stream ID matches the packet's stream ID and is non-zero.- Parameters:
conStreamId- the connection's send stream IDpacketStreamId- the packet's receive stream ID- Returns:
- true if stream IDs match and are non-zero, false otherwise