}
@Override
public synchronized void flush() throws IOException {
if (closed) {
throw new SshException("Already closed");
}
try {
while (bufferLength > 0) {
Buffer buf = buffer;
int total = bufferLength;
int length = Math.min(Math.min(remoteWindow.waitForSpace(), total), remoteWindow.getPacketSize());
int pos = buf.wpos();
buf.wpos(cmd == SshConstants.Message.SSH_MSG_CHANNEL_EXTENDED_DATA ? 14 : 10);
buf.putInt(length);
buf.wpos(buf.wpos() + length);
if (total == length) {
newBuffer(length);
} else {
int leftover = total - length;
newBuffer(Math.max(leftover, length));
buffer.putRawBytes(buf.array(), pos - leftover, leftover);
bufferLength = leftover;
}
lastSize = length;
remoteWindow.waitAndConsume(length);
log.debug("Send {} on channel {}", cmd, channel.getId());
channel.writePacket(buf);
}
} catch (WindowClosedException e) {
closed = true;
throw e;
} catch (SshException e) {
throw e;
} catch (Exception e) {
throw new SshException(e);
}
}