package ssh;

import java.io.*;
import java.net.*;
import java.util.*;
import java.math.*;

/**
 * This class represents an incoming ssh binary packet. It's
 * a subclass of DataInputStream, so you can pick out the packet fields
 * using the usual methods. This class also defines some methods
 * relevant to binary packets, such as ones that extract
 * multiple-precision integers in ssh format.<p>
 * 
 * A BinaryPacketIn object handles the type and data parts of an ssh
 * binary packet.<p>
 * 
 * Source: draft-ylonen-ssh-protocol-00.txt, page 3
 * 
 * @license This code is Copyright 1999 Jon Howell. It is available for
 * use under the GNU Public License, available at:
 * http://www.gnu.org/copyleft/gpl.html
 * 
 * @author Jon Howell <jonh@cs.dartmouth.edu> 
 * @rcs $Id: BinaryPacketIn.java,v 1.2 2000/05/22 01:35:46 jonh Exp $
 */
public class BinaryPacketIn
	extends DataInputStream {
					// DataInputStream starts at packet type
	byte body[];	// reference to the original packet data used to
					// construct the DataInputStream. Contains
					// padding, packet type, data, and CRC
	int length;
	int type;

	// public byte[] toByteArray() { return body; }

	public BinaryPacketIn(InputStream is, int length, byte[] body)
		throws IOException {
		super(is);

		this.body = body;
		this.length = length;
		type = readUnsignedByte();	// read a byte, treat it as an unsigned int
	}

	public int getType() { return type; }

	public String readString()
		throws IOException {
		// four-byte length,followed by length bytes of data
		return new String(readStringAsBytes());
	}

	public byte[] readStringAsBytes()
		throws IOException {
		int strLength = readInt();
		byte[] stringData = new byte[strLength];
		readFully(stringData, 0, strLength);
		return stringData;
	}

	public BigInteger readBigInteger()
		throws IOException {
		return StreamExtras.readBigInteger(this);
	}
}

// TODO: One potential problem with this code: I use readInt and Java
// ints all over to refer to ssh ints, which are unsigned. I don't think
// it matters, because packets (and hence strings inside packets) can't be
// bigger than 256K.

