Renamed some Buffer methods to better reflect the SSH datatype

This commit is contained in:
Shikhar Bhushan
2011-05-22 09:43:19 +01:00
parent 3c3715eccf
commit 17d8e91f05
25 changed files with 91 additions and 91 deletions

View File

@@ -222,7 +222,7 @@ public class Buffer<T extends Buffer<T>> {
* @return the byte-array read
*/
public byte[] readBytes() {
int len = readInt();
int len = readUInt32AsInt();
if (len < 0 || len > 32768)
throw new BufferException("Bad item length: " + len);
byte[] b = new byte[len];
@@ -251,7 +251,7 @@ public class Buffer<T extends Buffer<T>> {
* @return this
*/
public T putBytes(byte[] b, int off, int len) {
return putInt(len - off).putRawBytes(b, off, len);
return putUInt32(len - off).putRawBytes(b, off, len);
}
public void readRawBytes(byte[] buf) {
@@ -294,11 +294,11 @@ public class Buffer<T extends Buffer<T>> {
return (T) this;
}
public int readInt() {
return (int) readLong();
public int readUInt32AsInt() {
return (int) readUInt32();
}
public long readLong() {
public long readUInt32() {
ensureAvailable(4);
return data[rpos++] << 24 & 0xff000000L |
data[rpos++] << 16 & 0x00ff0000L |
@@ -314,7 +314,7 @@ public class Buffer<T extends Buffer<T>> {
* @return this
*/
@SuppressWarnings("unchecked")
public T putInt(long uint32) {
public T putUInt32(long uint32) {
ensureCapacity(4);
if (uint32 < 0 || uint32 > 0xffffffffL)
throw new BufferException("Invalid value: " + uint32);
@@ -356,10 +356,10 @@ public class Buffer<T extends Buffer<T>> {
int i = foo.length;
if ((foo[0] & 0x80) != 0) {
i++;
putInt(i);
putUInt32(i);
putByte((byte) 0);
} else
putInt(i);
putUInt32(i);
return putRawBytes(foo);
}
@@ -367,15 +367,15 @@ public class Buffer<T extends Buffer<T>> {
return readBytes();
}
public long readUINT64() {
long uint64 = (readLong() << 32) + (readLong() & 0xffffffffL);
public long readUInt64() {
long uint64 = (readUInt32() << 32) + (readUInt32() & 0xffffffffL);
if (uint64 < 0)
throw new BufferException("Cannot handle values > Long.MAX_VALUE");
return uint64;
}
@SuppressWarnings("unchecked")
public T putUINT64(long uint64) {
public T putUInt64(long uint64) {
if (uint64 < 0)
throw new BufferException("Invalid value: " + uint64);
data[wpos++] = (byte) (uint64 >> 56);
@@ -395,7 +395,7 @@ public class Buffer<T extends Buffer<T>> {
* @return the string as a Java {@code String}
*/
public String readString() {
int len = readInt();
int len = readUInt32AsInt();
if (len < 0 || len > 32768)
throw new BufferException("Bad item length: " + len);
ensureAvailable(len);
@@ -444,7 +444,7 @@ public class Buffer<T extends Buffer<T>> {
public T putSensitiveString(char[] str) {
if (str == null)
return putString("");
putInt(str.length);
putUInt32(str.length);
ensureCapacity(str.length);
for (char c : str)
data[wpos++] = (byte) c;

View File

@@ -103,7 +103,7 @@ public class ConnectionImpl
private Channel getChannel(SSHPacket buffer)
throws ConnectionException {
int recipient = buffer.readInt();
int recipient = buffer.readUInt32AsInt();
Channel channel = get(recipient);
if (channel != null)
return channel;
@@ -218,7 +218,7 @@ public class ConnectionImpl
openers.get(type).handleOpen(buf);
else {
log.warn("No opener found for `{}` CHANNEL_OPEN request -- rejecting", type);
sendOpenFailure(buf.readInt(), OpenFailException.Reason.UNKNOWN_CHANNEL_TYPE, "");
sendOpenFailure(buf.readUInt32AsInt(), OpenFailException.Reason.UNKNOWN_CHANNEL_TYPE, "");
}
}
@@ -226,8 +226,8 @@ public class ConnectionImpl
public void sendOpenFailure(int recipient, Reason reason, String message)
throws TransportException {
trans.write(new SSHPacket(Message.CHANNEL_OPEN_FAILURE)
.putInt(recipient)
.putInt(reason.getCode())
.putUInt32(recipient)
.putUInt32(reason.getCode())
.putString(message));
}

View File

@@ -183,11 +183,11 @@ public abstract class AbstractChannel
break;
case CHANNEL_EXTENDED_DATA:
gotExtendedData(buf.readInt(), buf);
gotExtendedData(buf.readUInt32AsInt(), buf);
break;
case CHANNEL_WINDOW_ADJUST:
gotWindowAdjustment(buf.readInt());
gotWindowAdjustment(buf.readUInt32AsInt());
break;
case CHANNEL_REQUEST:
@@ -333,12 +333,12 @@ public abstract class AbstractChannel
}
protected SSHPacket newBuffer(Message cmd) {
return new SSHPacket(cmd).putInt(recipient);
return new SSHPacket(cmd).putUInt32(recipient);
}
protected void receiveInto(ChannelInputStream stream, SSHPacket buf)
throws ConnectionException, TransportException {
final int len = buf.readInt();
final int len = buf.readUInt32AsInt();
if (len < 0 || len > getLocalMaxPacketSize() || len > buf.available())
throw new ConnectionException(DisconnectReason.PROTOCOL_ERROR, "Bad item length: " + len);
if (log.isTraceEnabled())

View File

@@ -163,7 +163,7 @@ public final class ChannelInputStream
if (adjustment > 0) {
log.info("Sending SSH_MSG_CHANNEL_WINDOW_ADJUST to #{} for {} bytes", chan.getRecipient(), adjustment);
trans.write(new SSHPacket(Message.CHANNEL_WINDOW_ADJUST)
.putInt(chan.getRecipient()).putInt(adjustment));
.putUInt32(chan.getRecipient()).putUInt32(adjustment));
win.expand(adjustment);
}
}

View File

@@ -74,8 +74,8 @@ public final class ChannelOutputStream
buffer.rpos(5);
buffer.wpos(5);
buffer.putMessageID(Message.CHANNEL_DATA);
buffer.putInt(0); // meant to be recipient
buffer.putInt(0); // meant to be data length
buffer.putUInt32(0); // meant to be recipient
buffer.putUInt32(0); // meant to be data length
}
@Override
@@ -153,8 +153,8 @@ public final class ChannelOutputStream
private void putRecipientAndLength() {
final int origPos = buffer.wpos();
buffer.wpos(6);
buffer.putInt(chan.getRecipient());
buffer.putInt(bufferLength);
buffer.putUInt32(chan.getRecipient());
buffer.putUInt32(bufferLength);
buffer.wpos(origPos);
}

View File

@@ -68,21 +68,21 @@ public abstract class AbstractDirectChannel
}
private void gotOpenConfirmation(SSHPacket buf) {
init(buf.readInt(), buf.readInt(), buf.readInt());
init(buf.readUInt32AsInt(), buf.readUInt32AsInt(), buf.readUInt32AsInt());
open.set();
}
private void gotOpenFailure(SSHPacket buf) {
open.deliverError(new OpenFailException(getType(), buf.readInt(), buf.readString()));
open.deliverError(new OpenFailException(getType(), buf.readUInt32AsInt(), buf.readString()));
finishOff();
}
protected SSHPacket buildOpenReq() {
return new SSHPacket(Message.CHANNEL_OPEN)
.putString(getType())
.putInt(getID())
.putInt(getLocalWinSize())
.putInt(getLocalMaxPacketSize());
.putUInt32(getID())
.putUInt32(getLocalWinSize())
.putUInt32(getLocalMaxPacketSize());
}
@Override

View File

@@ -59,9 +59,9 @@ public class LocalPortForwarder {
protected SSHPacket buildOpenReq() {
return super.buildOpenReq()
.putString(host)
.putInt(port)
.putUInt32(port)
.putString(ss.getInetAddress().getHostAddress())
.putInt(ss.getLocalPort());
.putUInt32(ss.getLocalPort());
}
}

View File

@@ -140,7 +140,7 @@ public enum PTYMode {
Buffer.PlainBuffer buf = new Buffer.PlainBuffer();
for (Entry<PTYMode, Integer> entry : modes.entrySet()) {
buf.putByte(entry.getKey().getOpcode());
buf.putInt(entry.getValue());
buf.putUInt32(entry.getValue());
}
buf.putByte((byte) 0);
return buf.getCompactData();

View File

@@ -86,10 +86,10 @@ public class SessionChannel
true,
new Buffer.PlainBuffer()
.putString(term)
.putInt(cols)
.putInt(rows)
.putInt(width)
.putInt(height)
.putUInt32(cols)
.putUInt32(rows)
.putUInt32(width)
.putUInt32(height)
.putBytes(PTYMode.encode(modes))
).await(conn.getTimeout(), TimeUnit.SECONDS);
}
@@ -106,10 +106,10 @@ public class SessionChannel
"pty-req",
false,
new Buffer.PlainBuffer()
.putInt(cols)
.putInt(rows)
.putInt(width)
.putInt(height)
.putUInt32(cols)
.putUInt32(rows)
.putUInt32(width)
.putUInt32(height)
);
}
@@ -150,7 +150,7 @@ public class SessionChannel
if ("xon-xoff".equals(req))
canDoFlowControl = buf.readBoolean();
else if ("exit-status".equals(req))
exitStatus = buf.readInt();
exitStatus = buf.readUInt32AsInt();
else if ("exit-signal".equals(req)) {
exitSignal = Signal.fromString(buf.readString());
wasCoreDumped = buf.readBoolean(); // core dumped
@@ -170,7 +170,7 @@ public class SessionChannel
.putBoolean(false)
.putString(authProto)
.putString(authCookie)
.putInt(screen)
.putUInt32(screen)
).await(conn.getTimeout(), TimeUnit.SECONDS);
}

View File

@@ -69,9 +69,9 @@ public abstract class AbstractForwardedChannel
// Must ensure channel is attached before confirming, data could start coming in immediately!
conn.attach(this);
trans.write(newBuffer(Message.CHANNEL_OPEN_CONFIRMATION)
.putInt(getID())
.putInt(getLocalWinSize())
.putInt(getLocalMaxPacketSize()));
.putUInt32(getID())
.putUInt32(getLocalWinSize())
.putUInt32(getLocalMaxPacketSize()));
open.set();
}

View File

@@ -168,7 +168,7 @@ public class RemotePortForwarder
throws ConnectionException, TransportException {
SSHPacket reply = req(PF_REQ, forward);
if (forward.port == 0)
forward.port = reply.readInt();
forward.port = reply.readUInt32AsInt();
log.info("Remote end listening on {}", forward);
listeners.put(forward, listener);
return forward;
@@ -193,7 +193,7 @@ public class RemotePortForwarder
protected SSHPacket req(String reqName, Forward forward)
throws ConnectionException, TransportException {
final byte[] specifics = new Buffer.PlainBuffer().putString(forward.address).putInt(forward.port)
final byte[] specifics = new Buffer.PlainBuffer().putString(forward.address).putUInt32(forward.port)
.getCompactData();
return conn.sendGlobalRequest(reqName, true, specifics)
.retrieve(conn.getTimeout(), TimeUnit.SECONDS);
@@ -211,9 +211,9 @@ public class RemotePortForwarder
@Override
public void handleOpen(SSHPacket buf)
throws ConnectionException, TransportException {
final ForwardedTCPIPChannel chan = new ForwardedTCPIPChannel(conn, buf.readInt(), buf.readInt(), buf.readInt(),
new Forward(buf.readString(), buf.readInt()),
buf.readString(), buf.readInt());
final ForwardedTCPIPChannel chan = new ForwardedTCPIPChannel(conn, buf.readUInt32AsInt(), buf.readUInt32AsInt(), buf.readUInt32AsInt(),
new Forward(buf.readString(), buf.readUInt32AsInt()),
buf.readString(), buf.readUInt32AsInt());
if (listeners.containsKey(chan.getParentForward()))
callListener(listeners.get(chan.getParentForward()), chan);
else

View File

@@ -56,9 +56,9 @@ public class X11Forwarder
public void handleOpen(SSHPacket buf)
throws ConnectionException, TransportException {
callListener(listener, new X11Channel(conn,
buf.readInt(),
buf.readInt(), buf.readInt(),
buf.readString(), buf.readInt()));
buf.readUInt32AsInt(),
buf.readUInt32AsInt(), buf.readUInt32AsInt(),
buf.readString(), buf.readUInt32AsInt()));
}
/** Stop handling {@code x11} channel open requests. De-registers itself with connection layer. */

View File

@@ -119,26 +119,26 @@ public final class FileAttributes {
public byte[] toBytes() {
Buffer.PlainBuffer buf = new Buffer.PlainBuffer();
buf.putInt(mask);
buf.putUInt32(mask);
if (has(Flag.SIZE))
buf.putUINT64(size);
buf.putUInt64(size);
if (has(Flag.UIDGID)) {
buf.putInt(uid);
buf.putInt(gid);
buf.putUInt32(uid);
buf.putUInt32(gid);
}
if (has(Flag.MODE))
buf.putInt(mode.getMask());
buf.putUInt32(mode.getMask());
if (has(Flag.ACMODTIME)) {
buf.putInt(atime);
buf.putInt(mtime);
buf.putUInt32(atime);
buf.putUInt32(mtime);
}
if (has(Flag.EXTENDED)) {
buf.putInt(ext.size());
buf.putUInt32(ext.size());
for (Entry<String, String> entry : ext.entrySet()) {
buf.putString(entry.getKey());
buf.putString(entry.getValue());

View File

@@ -37,7 +37,7 @@ public class RemoteDirectory
switch (res.getType()) {
case NAME:
final int count = res.readInt();
final int count = res.readUInt32AsInt();
for (int i = 0; i < count; i++) {
final String name = res.readString();
res.readString(); // long name - IGNORED - shdve never been in the protocol

View File

@@ -55,10 +55,10 @@ public class RemoteFile
public int read(long fileOffset, byte[] to, int offset, int len)
throws IOException {
Response res = requester.doRequest(newRequest(PacketType.READ).putUINT64(fileOffset).putInt(len));
Response res = requester.doRequest(newRequest(PacketType.READ).putUInt64(fileOffset).putUInt32(len));
switch (res.getType()) {
case DATA:
int recvLen = res.readInt();
int recvLen = res.readUInt32AsInt();
System.arraycopy(res.array(), res.rpos(), to, offset, recvLen);
return recvLen;
@@ -74,8 +74,8 @@ public class RemoteFile
public void write(long fileOffset, byte[] data, int off, int len)
throws IOException {
requester.doRequest(newRequest(PacketType.WRITE)
.putUINT64(fileOffset)
.putInt(len - off)
.putUInt64(fileOffset)
.putUInt32(len - off)
.putRawBytes(data, off, len)
).ensureStatusPacketIsOK();
}

View File

@@ -29,7 +29,7 @@ public class Request
this.type = type;
this.reqID = reqID;
responsePromise = new Promise<Response, SFTPException>("sftp / " + reqID, SFTPException.chainer);
putInt(reqID);
putUInt32(reqID);
}
public long getRequestID() {

View File

@@ -55,7 +55,7 @@ public class Response
super(pk);
this.protocolVersion = protocolVersion;
this.type = readType();
this.reqID = readLong();
this.reqID = readUInt32();
}
public int getProtocolVersion() {
@@ -71,7 +71,7 @@ public class Response
}
public StatusCode readStatusCode() {
return StatusCode.fromInt(readInt());
return StatusCode.fromInt(readUInt32AsInt());
}
public Response ensurePacketTypeIs(PacketType pt)

View File

@@ -65,7 +65,7 @@ public class SFTPEngine
public SFTPEngine init()
throws IOException {
transmit(new SFTPPacket<Request>(PacketType.INIT).putInt(MAX_SUPPORTED_VERSION));
transmit(new SFTPPacket<Request>(PacketType.INIT).putUInt32(MAX_SUPPORTED_VERSION));
final SFTPPacket<Response> response = reader.readPacket();
@@ -73,7 +73,7 @@ public class SFTPEngine
if (type != PacketType.VERSION)
throw new SFTPException("Expected INIT packet, received: " + type);
operativeVersion = response.readInt();
operativeVersion = response.readUInt32AsInt();
log.info("Server version {}", operativeVersion);
if (MAX_SUPPORTED_VERSION < operativeVersion)
throw new SFTPException("Server reported incompatible protocol version: " + operativeVersion);
@@ -120,7 +120,7 @@ public class SFTPEngine
public RemoteFile open(String path, Set<OpenMode> modes, FileAttributes fa)
throws IOException {
final String handle = doRequest(
newRequest(PacketType.OPEN).putString(path).putInt(OpenMode.toMask(modes)).putFileAttributes(fa)
newRequest(PacketType.OPEN).putString(path).putUInt32(OpenMode.toMask(modes)).putFileAttributes(fa)
).ensurePacketTypeIs(PacketType.HANDLE).readString();
return new RemoteFile(this, path, handle);
}
@@ -244,7 +244,7 @@ public class SFTPEngine
protected static String readSingleName(Response res)
throws IOException {
res.ensurePacketTypeIs(PacketType.NAME);
if (res.readInt() == 1)
if (res.readUInt32AsInt() == 1)
return res.readString();
else
throw new SFTPException("Unexpected data in " + res.getType() + " packet");

View File

@@ -35,17 +35,17 @@ public class SFTPPacket<T extends SFTPPacket<T>>
public FileAttributes readFileAttributes() {
final FileAttributes.Builder builder = new FileAttributes.Builder();
final int mask = readInt();
final int mask = readUInt32AsInt();
if (FileAttributes.Flag.SIZE.isSet(mask))
builder.withSize(readUINT64());
builder.withSize(readUInt64());
if (FileAttributes.Flag.UIDGID.isSet(mask))
builder.withUIDGID(readInt(), readInt());
builder.withUIDGID(readUInt32AsInt(), readUInt32AsInt());
if (FileAttributes.Flag.MODE.isSet(mask))
builder.withPermissions(readInt());
builder.withPermissions(readUInt32AsInt());
if (FileAttributes.Flag.ACMODTIME.isSet(mask))
builder.withAtimeMtime(readInt(), readInt());
builder.withAtimeMtime(readUInt32AsInt(), readUInt32AsInt());
if (FileAttributes.Flag.EXTENDED.isSet(mask)) {
final int extCount = readInt();
final int extCount = readUInt32AsInt();
for (int i = 0; i < extCount; i++)
builder.withExtended(readString(), readString());
}

View File

@@ -157,7 +157,7 @@ final class Decoder
throws TransportException {
cipher.update(inputBuffer.array(), 0, cipherSize);
final int len = inputBuffer.readInt(); // Read packet length
final int len = inputBuffer.readUInt32AsInt(); // Read packet length
if (isInvalidPacketLength(len)) { // Check packet length validity
log.info("Error decoding packet (invalid length) {}", inputBuffer.printHex());

View File

@@ -116,7 +116,7 @@ final class Encoder
// Put packet header
buffer.wpos(startOfPacket);
buffer.putInt(packetLen);
buffer.putUInt32(packetLen);
buffer.putByte((byte) padLen);
// Now wpos will mark end of padding

View File

@@ -82,7 +82,7 @@ class Proposal {
packet.putString("");
packet.putBoolean(false); // Optimistic next packet does not follow
packet.putInt(0); // "Reserved" for future by spec
packet.putUInt32(0); // "Reserved" for future by spec
}
public Proposal(SSHPacket packet) {

View File

@@ -345,7 +345,7 @@ public final class TransportImpl
throws TransportException {
final long seq = decoder.getSequenceNumber();
log.info("Sending SSH_MSG_UNIMPLEMENTED for packet #{}", seq);
return write(new SSHPacket(Message.UNIMPLEMENTED).putInt(seq));
return write(new SSHPacket(Message.UNIMPLEMENTED).putUInt32(seq));
}
@Override
@@ -438,7 +438,7 @@ public final class TransportImpl
log.debug("Sending SSH_MSG_DISCONNECT: reason=[{}], msg=[{}]", reason, message);
try {
write(new SSHPacket(Message.DISCONNECT)
.putInt(reason.toInt())
.putUInt32(reason.toInt())
.putString(message)
.putString(""));
} catch (IOException worthless) {
@@ -509,7 +509,7 @@ public final class TransportImpl
private void gotDisconnect(SSHPacket buf)
throws TransportException {
DisconnectReason code = DisconnectReason.fromInt(buf.readInt());
DisconnectReason code = DisconnectReason.fromInt(buf.readUInt32AsInt());
String message = buf.readString();
log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, message);
throw new TransportException(code, "Disconnected; server said: " + message);
@@ -537,7 +537,7 @@ public final class TransportImpl
*/
private void gotUnimplemented(SSHPacket buf)
throws SSHException {
long seqNum = buf.readLong();
long seqNum = buf.readUInt32();
log.info("Received SSH_MSG_UNIMPLEMENTED #{}", seqNum);
if (kexer.isKexOngoing())
throw new TransportException("Received SSH_MSG_UNIMPLEMENTED while exchanging keys");

View File

@@ -65,7 +65,7 @@ public class AuthKeyboardInteractive
} else {
provider.init(makeAccountResource(), buf.readString(), buf.readString());
buf.readString(); // lang-tag
final int numPrompts = buf.readInt();
final int numPrompts = buf.readUInt32AsInt();
final CharArrWrap[] userReplies = new CharArrWrap[numPrompts];
for (int i = 0; i < numPrompts; i++) {
final String prompt = buf.readString();
@@ -79,7 +79,7 @@ public class AuthKeyboardInteractive
private void respond(CharArrWrap[] userReplies)
throws TransportException {
final SSHPacket pkt = new SSHPacket(Message.USERAUTH_INFO_RESPONSE).putInt(userReplies.length);
final SSHPacket pkt = new SSHPacket(Message.USERAUTH_INFO_RESPONSE).putUInt32(userReplies.length);
for (final CharArrWrap response : userReplies)
pkt.putSensitiveString(response.arr);
params.getTransport().write(pkt);

View File

@@ -59,7 +59,7 @@ public class BufferTest {
assertEquals(handyBuf.putString("some string").readString(), "some string");
// uint32
assertEquals(handyBuf.putInt(0xffffffffL).readLong(), 0xffffffffL);
assertEquals(handyBuf.putUInt32(0xffffffffL).readUInt32(), 0xffffffffL);
}
@Test