java.lang.Object
net.i2p.sam.SAMHandler
net.i2p.sam.SAMv1Handler
- All Implemented Interfaces:
Runnable, Handler, SAMDatagramReceiver, SAMRawReceiver, SAMStreamReceiver
- Direct Known Subclasses:
SAMv2Handler, SAMv3Handler
class SAMv1Handlerextends SAMHandler implements SAMRawReceiver, SAMDatagramReceiver, SAMStreamReceiver
Class able to handle a SAM version 1 client connections.
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final AtomicLongCounts the sessions created.protected final longIdentifier of this connection, unique among a router's SAM handlers.protected SAMMessageSessThe session used for datagram style messages.private static final intHow long the first read may wait - 60 seconds.protected SAMMessageSessThe SAM raw and datagram session, held after a successful HELLO.protected static final StringReply sent to a SESSION CREATE whose stream could not be established.protected SAMStreamSessionThe session used for STREAM CONNECT connections.Fields inherited from class SAMHandler
_log, bridge, i2cpProps, socket, stopHandler, stopLock, thread, verMajor, verMinorModifier and TypeFieldDescriptionprotected final LogLog scoped to this handler's class.protected final SAMBridgeRouter bridge this handler routes sessions over.protected final PropertiesI2CP options configuring the I2CP connection (port, host, numHops, etc).protected final SocketChannelClient channel this handler reads commands from.protected booleanWhether shutdown has been requested for this handler.protected final ObjectMonitor guarding the stop flag.protected I2PAppThreadThread running the SAM protocol loop for this connection.final intMajor version this handler was negotiated at.final intMinor version this handler was negotiated at.Constructor Summary
ConstructorsConstructorDescriptionSAMv1Handler(SocketChannel s, int verMajor, int verMinor, Properties i2cpProps, SAMBridge parent) Create a new SAM version 1 handler.SAMv1Handler(SocketChannel s, int verMajor, int verMinor, SAMBridge parent) Create a new SAM version 1 handler.Method Summary
Modifier and TypeMethodDescriptionprivate booleancheckDatagramSize(int size) Check whether a size is inside the limits allowed by this protocol.private booleancheckSize(int size) Check whether a size is inside the limits allowed by this protocol.protected static StringCreate a string to be appended to a status.protected booleanexecDatagramMessage(String opcode, Properties props) Parse and execute a DATAGRAM message.protected booleanexecDestMessage(String opcode, Properties props) Parse and execute a DEST message.private booleanexecDgOrRawMessage(boolean isRaw, String opcode, Properties props) Runs a datagram or raw message command.protected booleanexecNamingMessage(String opcode, Properties props) Parse and execute a NAMING message.protected booleanexecRawMessage(String opcode, Properties props) Parse and execute a RAW message.protected booleanexecSessionMessage(String opcode, Properties props) Parse and execute a SESSION message.protected booleanexecStreamClose(Properties props) Parse and execute a STREAM CLOSE message.protected booleanexecStreamConnect(Properties props) Parse and execute a STREAM CONNECT message.protected booleanexecStreamMessage(String opcode, Properties props) Parse and execute a STREAM message.protected booleanexecStreamSend(Properties props) Parse and execute a STREAM SEND message.protected final SAMMessageSessReturn the datagram session.protected final SAMMessageSessReturn the raw session.protected final SAMStreamSessionReturn the stream session.voidhandle()Handle a SAM v1 client connection by reading and dispatching commands in a loop until the connection is closed or an error occurs.private SAMStreamSessionnewSAMStreamSession(String destKeystream, String direction, Properties props) Opens a stream session for the destination named on the command line.voidnotifyStreamDisconnection(int id, String result, String msg) Notify the SAM client that a stream connection has been disconnected.voidnotifyStreamIncomingConnection(int id, Destination d) Notify the SAM client of an incoming stream connection.voidnotifyStreamOutgoingConnection(int id, String result, String msg) Report the result of an outgoing stream connection.voidnotifyStreamSendBufferFree(int id) Notify the SAM client that the stream send buffer is free for more data.voidreceiveDatagramBytes(Destination sender, byte[] data, int proto, int fromPort, int toPort) Receive datagram bytes from the network and forward them to the SAM client.voidreceiveRawBytes(byte[] data, int proto, int fromPort, int toPort) Receive raw bytes from the network and forward them to the SAM client.voidreceiveStreamBytes(int id, ByteBuffer data) Receive stream bytes from the network and forward them to the SAM client.voidStop receiving datagram bytes and close the client socket.voidStop receiving raw bytes and close the client socket.voidStop receiving stream bytes and close the client socket.voidstreamSendAnswer(int id, String result, String bufferState) Notify the SAM client of the result of a stream SEND operation.booleanVerify the SAM protocol version is supported by this handler.protected booleanwriteString(String s, String msg) Write a string and message, escaping the message.Methods inherited from class SAMHandler
closeClientSocket, getAuthUser, getClientSocket, getRemoteAddrPort, getWriteLock, isLoopbackAddress, logSessionError, run, sameClient, sameClient, setAuthUser, shouldStop, startHandling, stopHandling, toString, writeBytes, writeString, writeStringModifier and TypeMethodDescriptionprotected final voidClose the socket connected to the SAM client.(package private) final StringGet the username this connection authenticated with, if any.protected final SocketChannelGet the channel of the socket connected to the SAM client.(package private) final StringGet the remote address and port of this connection, bracketing IPv6, for rejection and ban logging.protected ObjectIf you're crazy enough to write to the raw socket, grab the write lock withSAMHandler.getWriteLock(), synchronize against it, and write to the getOut().(package private) static booleanisLoopbackAddress(String host) Determine whether an address is a loopback address, in any of the forms the platform may report it.protected voidlogSessionError(String msg, Exception e) Log a session startup failure.final voidrun()Register with the bridge, callSAMHandler.handle(), unregister with the bridge.(package private) static booleansameClient(String myAuthUser, String otherAuthUser, String myHost, String otherHost) Decide whether two SAM connections belong to the same client.(package private) final booleansameClient(SAMHandler other) Determine whether two connections belong to the same client, which is what decides whether one of them may use a session nickname owned by the other.(package private) final voidsetAuthUser(String user) Record the username this connection authenticated with.protected final booleanShould the handler be stopped?voidStart handling the SAM connection, detaching a handling thread.voidStop the SAM handler, close the client socket, unregister with the bridge.final StringtoString()Get a string describing the handler.protected final voidwriteBytes(ByteBuffer data) Write a byte array on the handler's socket.protected final booleanwriteString(String str) Write a string to the handler's socket.static booleanwriteString(String str, SocketChannel out) Unsynchronized, use with caution.
Field Details
rawSession
The SAM raw and datagram session, held after a successful HELLO.datagramSession
The session used for datagram style messages.streamSession
The session used for STREAM CONNECT connections._id
protected final long _idIdentifier of this connection, unique among a router's SAM handlers.__id
Counts the sessions created.FIRST_READ_TIMEOUT
private static final int FIRST_READ_TIMEOUTHow long the first read may wait - 60 seconds.- See Also:
SESSION_ERROR
Reply sent to a SESSION CREATE whose stream could not be established.- See Also:
Constructor Details
SAMv1Handler
public SAMv1Handler(SocketChannel s, int verMajor, int verMinor, SAMBridge parent) throws SAMException, IOException Create a new SAM version 1 handler. This constructor expects that the SAM HELLO message has been still answered (and stripped) from the socket input stream.- Parameters:
s- Socket attached to a SAM clientverMajor- SAM major version to manage (should be 1)verMinor- SAM minor version to manageparent- the SAM bridge managing this handler- Throws:
SAMException- if the version is not supportedIOException- if an I/O error occurs
SAMv1Handler
public SAMv1Handler(SocketChannel s, int verMajor, int verMinor, Properties i2cpProps, SAMBridge parent) throws SAMException, IOException Create a new SAM version 1 handler. This constructor expects that the SAM HELLO message has been still answered (and stripped) from the socket input stream.- Parameters:
s- Socket attached to a SAM clientverMajor- SAM major version to manage (should be 1)verMinor- SAM minor version to managei2cpProps- properties to configure the I2CP connection (host, port, etc)parent- the SAM bridge managing this handler- Throws:
SAMException- if the version is not supportedIOException- if an I/O error occurs
Method Details
getRawSession
getDatagramSession
Return the datagram session.- Returns:
- the datagram session
getStreamSession
Return the stream session.- Returns:
- the stream session
verifVersion
public boolean verifVersion()Verify the SAM protocol version is supported by this handler.- Returns:
- true if the major version matches this handler's version
handle
public void handle()Handle a SAM v1 client connection by reading and dispatching commands in a loop until the connection is closed or an error occurs.- Specified by:
handlein classSAMHandler
execSessionMessage
Parse and execute a SESSION message.- Parameters:
opcode- the SESSION sub-command (e.g. CREATE)props- the parsed message properties- Returns:
- true if the handler should continue processing commands
newSAMStreamSession
private SAMStreamSession newSAMStreamSession(String destKeystream, String direction, Properties props) throws IOException, DataFormatException, SAMException Opens a stream session for the destination named on the command line.- Parameters:
destKeystream- the destination and key parameters from the command linedirection- whether the session is client or serverprops- the parameters of the session- Returns:
- the new stream session
- Throws:
IOException- if the session cannot talk to the routerDataFormatException- if the destination keys are invalidSAMException- if the session cannot be set up
execDestMessage
Parse and execute a DEST message.- Parameters:
opcode- the DEST sub-command (e.g. GENERATE)props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execNamingMessage
Parse and execute a NAMING message.- Parameters:
opcode- the NAMING sub-command (e.g. LOOKUP)props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execDatagramMessage
Parse and execute a DATAGRAM message.- Parameters:
opcode- the DATAGRAM sub-command (e.g. SEND)props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execRawMessage
Parse and execute a RAW message.- Parameters:
opcode- the RAW sub-command (e.g. SEND)props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execDgOrRawMessage
Runs a datagram or raw message command.- Parameters:
isRaw- true for the raw message formopcode- the name of the commandprops- the parameters of the command- Returns:
- true if the command ran
execStreamMessage
Parse and execute a STREAM message.- Parameters:
opcode- the STREAM sub-command (e.g. SEND, CONNECT, CLOSE)props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execStreamSend
Parse and execute a STREAM SEND message.- Parameters:
props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execStreamConnect
Parse and execute a STREAM CONNECT message.- Parameters:
props- the parsed message properties- Returns:
- true if the handler should continue processing commands
execStreamClose
Parse and execute a STREAM CLOSE message.- Parameters:
props- the parsed message properties- Returns:
- true if the handler should continue processing commands
checkSize
private boolean checkSize(int size) Check whether a size is inside the limits allowed by this protocol.- Parameters:
size- the payload length in bytes, which must fall between 1 and 32768 inclusive- Returns:
- true if the size is within stream protocol limits
checkDatagramSize
private boolean checkDatagramSize(int size) Check whether a size is inside the limits allowed by this protocol.- Parameters:
size- the payload length in bytes, which must fall between 1 and 31744 inclusive- Returns:
- true if the size is within datagram protocol limits
receiveRawBytes
Receive raw bytes from the network and forward them to the SAM client.- Specified by:
receiveRawBytesin interfaceSAMRawReceiver- Parameters:
data- the received raw dataproto- the protocol numberfromPort- the source porttoPort- the destination port- Throws:
IOException- if writing to the client socket fails
stopRawReceiving
public void stopRawReceiving()Stop receiving raw bytes and close the client socket.- Specified by:
stopRawReceivingin interfaceSAMRawReceiver
receiveDatagramBytes
public void receiveDatagramBytes(Destination sender, byte[] data, int proto, int fromPort, int toPort) throws IOException Receive datagram bytes from the network and forward them to the SAM client.- Specified by:
receiveDatagramBytesin interfaceSAMDatagramReceiver- Parameters:
sender- the destination of the datagram senderdata- the received datagram dataproto- the protocol numberfromPort- the source porttoPort- the destination port- Throws:
IOException- if writing to the client socket fails
stopDatagramReceiving
public void stopDatagramReceiving()Stop receiving datagram bytes and close the client socket.- Specified by:
stopDatagramReceivingin interfaceSAMDatagramReceiver
streamSendAnswer
Notify the SAM client of the result of a stream SEND operation.- Specified by:
streamSendAnswerin interfaceSAMStreamReceiver- Parameters:
id- the stream connection IDresult- the result code (e.g. OK, TIMEOUT)bufferState- the current buffer state- Throws:
IOException- if writing to the client socket fails
notifyStreamSendBufferFree
Notify the SAM client that the stream send buffer is free for more data.- Specified by:
notifyStreamSendBufferFreein interfaceSAMStreamReceiver- Parameters:
id- the stream connection ID- Throws:
IOException- if writing to the client socket fails
notifyStreamIncomingConnection
Notify the SAM client of an incoming stream connection.- Specified by:
notifyStreamIncomingConnectionin interfaceSAMStreamReceiver- Parameters:
id- the stream connection IDd- the destination of the remote peer- Throws:
IOException- if writing to the client socket fails
notifyStreamOutgoingConnection
Report the result of an outgoing stream connection.- Specified by:
notifyStreamOutgoingConnectionin interfaceSAMStreamReceiver- Parameters:
id- New connection idresult- status code sent in the STREAM STATUS replymsg- may be null- Throws:
IOException- if writing to the client socket fails
createMessageString
writeString
Write a string and message, escaping the message. Writes s + createMessageString(msg) + \n.- Parameters:
s- The string, non-nullmsg- the message to escape and append as a MESSAGE= field, or null for no message- Returns:
- true if the composed line was written to the client socket
receiveStreamBytes
Receive stream bytes from the network and forward them to the SAM client.- Specified by:
receiveStreamBytesin interfaceSAMStreamReceiver- Parameters:
id- the stream connection IDdata- the received data- Throws:
IOException- if writing to the client socket fails
notifyStreamDisconnection
Notify the SAM client that a stream connection has been disconnected.- Specified by:
notifyStreamDisconnectionin interfaceSAMStreamReceiver- Parameters:
id- the stream connection IDresult- the result code (e.g. OK, TIMEOUT)msg- optional message, may be null- Throws:
IOException- if writing to the client socket fails
stopStreamReceiving
public void stopStreamReceiving()Stop receiving stream bytes and close the client socket.- Specified by:
stopStreamReceivingin interfaceSAMStreamReceiver