package ssh;

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

/**
 * This class writes data to an ssh stream. It creates a
 * BinaryPacketOut ssh packet for each write request, and sends it down
 * the BinaryPacketOutputStream. One way to get your hands on an
 * instance of this class is by calling connect() and then
 * getOutputStream() on an {@link ssh.ClientProtocol}.
 * 
 * @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: SshOutputStream.java,v 1.3 2000/05/22 01:36:02 jonh Exp $
 */
public class SshOutputStream
	extends OutputStream {

	BinaryPacketOutputStream binaryOut;
	byte[] buf;
	int bufoff, buflen;
	byte[] oneByteBuffer;
	int packetType;

	public SshOutputStream(BinaryPacketOutputStream binaryOut) {
		this.binaryOut = binaryOut;
		bufoff = 0;
		buflen = 0;
		oneByteBuffer = new byte[1];
		packetType = Protocol.SSH_CMSG_STDIN_DATA;
	}

	public void setType(int type) {
		// set type of packet transmitted; matters if actually talking
		// ssh 1.5 protocol. (I reuse this stream in my Snowflake stuff,
		// where it's "STDIN_DATA" both ways.)
		this.packetType = type;
	}

	public void write(int b)
		throws IOException {
		oneByteBuffer[0] = (byte) b;
		write(oneByteBuffer, 0, 1);
	}

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

		BinaryPacketOut bpo = binaryOut.newPacket();
		bpo.setType(packetType);
		bpo.writeStringAsBytes(b, off, len);
		binaryOut.writePacket(bpo);
		SecureRMIProtocol.log.log("packets",
			"SshOutputStream: wrote packet["+len+"] to BinaryPacketOutputStream");
	}

	public void close()
		throws IOException {
		BinaryPacketOut bpo = binaryOut.newPacket();
		bpo.setType(Protocol.SSH_MSG_DISCONNECT);
		binaryOut.writePacket(bpo);
	}
}
