package ssh;

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

/**
 * Objects of this class are DataOutputStreams so they can be
 * conveniently packed with data; then they are passed to a
 * BinaryPacketOutputStream to be sent over an ssh binary packet
 * stream.<p>
 * 
 * A BinaryPacketOut object handles the type and data parts of an ssh
 * binary packet.<p>
 * 
 * Source: draft-ylonen-ssh-protocol-00.txt, pages 3-4. 
 * 
 * @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<p>
 *
 * @author Jon Howell <jonh@cs.dartmouth.edu>
 * @rcs $Id: BinaryPacketOut.java,v 1.3 2000/05/22 01:35:47 jonh Exp $
 */

public class BinaryPacketOut
	extends DataOutputStream {

	boolean typeSet;

	private ByteArrayOutputStream baos;

	public static BinaryPacketOut newBinaryPacketOut()
		throws IOException {
		BinaryPacketOut bpo = new BinaryPacketOut(new ByteArrayOutputStream());
		return bpo;
	}

	public BinaryPacketOut(ByteArrayOutputStream os)
		throws IOException {
		super(os);
		baos = os;
		typeSet = false;
	}

	public void setType(int type)
		throws IOException {
		if (baos.size()>0) {
			throw new IOException("too late to set type");
		}
		writeByte((byte) type);
		typeSet = true;
	}

	public byte[] toByteArray()
		throws IOException {
		if (!typeSet) {
			throw new IOException("type field not set");
		}
		return baos.toByteArray();
	}

	public void writeString(String str)
		throws IOException {
		// four-byte length,followed by length bytes of data
		writeInt(str.length());
		write(str.getBytes());
	}

	public void writeStringAsBytes(byte[] b, int off, int len)
		throws IOException {
		writeInt(len);
		write(b, off, len);
	}

	public void writeBigInteger(BigInteger bi)
		throws IOException {

		StreamExtras.writeBigInteger(this, bi);
	}
}
