protected void handleWriteDataSuccess(byte cmd, byte[] data, int off, int len) { Session session = getSession(); try { Window wLocal = getLocalWindow(); wLocal.consumeAndCheck(len); } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("handleWriteDataSuccess({})[{}] failed ({}) to consume len={}: {}", this, SshConstants.getCommandMessageName(cmd & 0xFF), e.getClass().getSimpleName(), len, e.getMessage()); } session.exceptionCaught(e); } }
public void init(long size, long packetSize, PropertyResolver resolver) { BufferUtils.validateUint32Value(size, "Illegal initial size: %d"); BufferUtils.validateUint32Value(packetSize, "Illegal packet size: %d"); ValidateUtils.checkTrue(packetSize > 0L, "Packet size must be positive: %d", packetSize); long limitPacketSize = resolver.getLongProperty(FactoryManager.LIMIT_PACKET_SIZE, FactoryManager.DEFAULT_LIMIT_PACKET_SIZE); if (packetSize > limitPacketSize) { throw new IllegalArgumentException("Requested packet size (" + packetSize + ") exceeds max. allowed: " + limitPacketSize); } synchronized (lock) { this.maxSize = size; this.packetSize = packetSize; updateSize(size); } boolean debugEnabled = log.isDebugEnabled(); if (initialized.getAndSet(true)) { if (debugEnabled) { log.debug("init({}) re-initializing", this); } } if (debugEnabled) { log.debug("init({}) size={}, max={}, packet={}", this, getSize(), getMaxSize(), getPacketSize()); } }
protected AbstractChannel(String discriminator, boolean client, Collection<? extends RequestHandler<Channel>> handlers, CloseableExecutorService executorService) { super(discriminator); gracefulFuture = new DefaultCloseFuture(discriminator, lock); localWindow = new Window(this, null, client, true); remoteWindow = new Window(this, null, client, false); channelListenerProxy = EventListenerUtils.proxyWrapper(ChannelListener.class, getClass().getClassLoader(), channelListeners); executor = executorService; addRequestHandlers(handlers); }
public void consumeAndCheck(long len) throws IOException { synchronized (lock) { try { consume(len); check(maxSize); } catch (RuntimeException e) { throw new StreamCorruptedException("consumeAndCheck(" + this + ")" + " failed (" + e.getClass().getSimpleName() + ")" + " to consume " + len + " bytes" + ": " + e.getMessage()); } } }
/** * Waits until some data becomes available or timeout expires * * @param maxWaitTime Max. time (millis) to wait for space to become available * @return Amount of available data - always positive * @throws InterruptedException If interrupted while waiting * @throws WindowClosedException If window closed while waiting * @throws SocketTimeoutException If timeout expired before space became available * @see #waitForCondition(Predicate, long) */ public long waitForSpace(long maxWaitTime) throws InterruptedException, WindowClosedException, SocketTimeoutException { checkInitialized("waitForSpace"); long available; synchronized (lock) { waitForCondition(SPACE_AVAILABLE_PREDICATE, maxWaitTime); available = size; } if (log.isDebugEnabled()) { log.debug("waitForSpace({}) available: {}", this, available); } return available; }
public void consume(long len) { BufferUtils.validateUint32Value(len, "Invalid consumption length: %d"); checkInitialized("consume"); long remainLen; synchronized (lock) { remainLen = size - len; if (remainLen >= 0L) { updateSize(remainLen); } } if (remainLen < 0L) { throw new IllegalStateException("consume(" + this + ") required length (" + len + ") above available: " + (remainLen + len)); } if (log.isTraceEnabled()) { log.trace("Consume {} by {} down to {}", this, len, remainLen); } }
@Override public synchronized OpenFuture open() throws IOException { InetSocketAddress remote = (InetSocketAddress) serverSession.getRemoteAddress(); if (closeFuture.isClosed()) { throw new SshException("Session has been closed"); } openFuture = new DefaultOpenFuture(remote, lock); Session session = getSession(); if (log.isDebugEnabled()) { log.debug("open({}) SSH_MSG_CHANNEL_OPEN", this); } InetAddress remoteAddress = remote.getAddress(); String remoteHost = remoteAddress.getHostAddress(); Window wLocal = getLocalWindow(); String type = getChannelType(); Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN, remoteHost.length() + type.length() + Integer.SIZE); buffer.putString(type); buffer.putInt(getId()); buffer.putInt(wLocal.getSize()); buffer.putInt(wLocal.getPacketSize()); buffer.putString(remoteHost); buffer.putInt(remote.getPort()); writePacket(buffer); return openFuture; }
private static void waitForWindowEquals(Window w1, Window w2, String n1, String n2, long maxWait) throws InterruptedException { for (long waited = 0L, maxWaitNanos = TimeUnit.MILLISECONDS.toNanos(maxWait); waited < maxWaitNanos;) { if (w1.getSize() == w2.getSize()) { return; } long nanoStart = System.nanoTime(); Thread.sleep(1L); long nanoEnd = System.nanoTime(); long nanoDuration = nanoEnd - nanoStart; waited += nanoDuration; } // one last chance ... assertEquals(n1 + " and " + n2, w1.getSize(), w2.getSize()); }
long l2 = Math.min(l, Math.min(remoteWindow.getSize() + lastSize, remoteWindow.getPacketSize()) - bufferLength); if (l2 <= 0) { if (bufferLength > 0) { session.resetIdleTimeout(); try { long available = remoteWindow.waitForSpace(maxWaitTimeout); if (traceEnabled) { log.trace("write({}) len={} - available={}", this, l, available);
Channel channel = getChannel(); Window remoteWindow = channel.getRemoteWindow(); long length = Math.min(Math.min(remoteWindow.getSize(), total), remoteWindow.getPacketSize()); if (log.isTraceEnabled()) { log.trace("doWriteIfPossible({})[resume={}] attempting to write {} out of {}", this, resume, length, total); buf.putRawBytes(buffer.array(), buffer.rpos(), (int) length); buffer.rpos(buffer.rpos() + (int) length); remoteWindow.consume(length);
if ((buffer.rpos() > localWindow.getPacketSize()) || (buffer.available() == 0)) { buffer.compact(); lock.unlock(); localWindow.consumeAndCheck(len); return len;
public void check(long maxFree) throws IOException { BufferUtils.validateUint32Value(maxFree, "Invalid check size: %d"); checkInitialized("check"); long adjustSize = -1L; AbstractChannel channel = getChannel(); synchronized (lock) { // TODO make the adjust factor configurable via FactoryManager property long size = this.size; if (size < (maxFree / 2)) { adjustSize = maxFree - size; channel.sendWindowAdjust(adjustSize); updateSize(maxFree); } } if (adjustSize >= 0L) { if (log.isDebugEnabled()) { log.debug("Increase {} by {} up to {}", this, adjustSize, maxFree); } } }
/** * Waits for enough data to become available to consume the specified size * * @param len Size of data to consume * @param maxWaitTime ax. time (millis) to wait for enough data to become available * @throws InterruptedException If interrupted while waiting * @throws WindowClosedException If window closed while waiting * @throws SocketTimeoutException If timeout expired before enough data became available * @see #waitForCondition(Predicate, long) * @see #consume(long) */ public void waitAndConsume(long len, long maxWaitTime) throws InterruptedException, WindowClosedException, SocketTimeoutException { BufferUtils.validateUint32Value(len, "Invalid wait consume length: %d", len); checkInitialized("waitAndConsume"); boolean debugEnabled = log.isDebugEnabled(); synchronized (lock) { waitForCondition(input -> { // NOTE: we do not call "getSize()" on purpose in order to avoid the lock return input.size >= len; }, maxWaitTime); if (debugEnabled) { log.debug("waitAndConsume({}) - requested={}, available={}", this, len, size); } consume(len); } }
long available; try { available = remoteWindow.waitForSpace(maxWaitTimeout); if (traceEnabled) { log.trace("flush({}) len={}, available={}", this, total, available); long length = Math.min(lenToSend, remoteWindow.getPacketSize()); if (length > Integer.MAX_VALUE) { throw new StreamCorruptedException("Accumulated " + SshConstants.getCommandMessageName(cmd) remoteWindow.waitAndConsume(length, maxWaitTimeout); if (traceEnabled) { log.trace("flush({}) send {} len={}", channel, SshConstants.getCommandMessageName(cmd), length);
Session session = getSession(); Window wRemote = getRemoteWindow(); long packetSize = wRemote.getPacketSize(); ValidateUtils.checkTrue(packetSize < Integer.MAX_VALUE, "Remote packet size exceeds int boundary: %d", packetSize); byte[] buffer = new byte[(int) packetSize];
@Override public String toString() { return getClass().getSimpleName() + "[" + suffix + "](" + getChannel() + ")"; } }
@Override public void handleWindowAdjust(Buffer buffer) throws IOException { int window = buffer.getInt(); if (log.isDebugEnabled()) { log.debug("handleWindowAdjust({}) SSH_MSG_CHANNEL_WINDOW_ADJUST window={}", this, window); } Window wRemote = getRemoteWindow(); wRemote.expand(window); notifyStateChanged("SSH_MSG_CHANNEL_WINDOW_ADJUST"); }
@Override public synchronized OpenFuture open() throws IOException { InetSocketAddress remote = (InetSocketAddress) serverSession.getRemoteAddress(); if (closeFuture.isClosed()) { throw new SshException("Session has been closed"); } openFuture = new DefaultOpenFuture(remote, lock); Session session = getSession(); if (log.isDebugEnabled()) { log.debug("open({}) SSH_MSG_CHANNEL_OPEN", this); } InetAddress remoteAddress = remote.getAddress(); String remoteHost = remoteAddress.getHostAddress(); Window wLocal = getLocalWindow(); String type = getChannelType(); Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN, remoteHost.length() + type.length() + Integer.SIZE); buffer.putString(type); buffer.putInt(getId()); buffer.putInt(wLocal.getSize()); buffer.putInt(wLocal.getPacketSize()); buffer.putString(remoteHost); buffer.putInt(remote.getPort()); writePacket(buffer); return openFuture; }
private static void waitForWindowEquals(Window w1, Window w2, String n1, String n2, long maxWait) throws InterruptedException { for (long waited = 0L, maxWaitNanos = TimeUnit.MILLISECONDS.toNanos(maxWait); waited < maxWaitNanos;) { if (w1.getSize() == w2.getSize()) { return; } long nanoStart = System.nanoTime(); Thread.sleep(1L); long nanoEnd = System.nanoTime(); long nanoDuration = nanoEnd - nanoStart; waited += nanoDuration; } // one last chance ... assertEquals(n1 + " and " + n2, w1.getSize(), w2.getSize()); }
long l2 = Math.min(l, Math.min(remoteWindow.getSize() + lastSize, remoteWindow.getPacketSize()) - bufferLength); if (l2 <= 0) { if (bufferLength > 0) { session.resetIdleTimeout(); try { long available = remoteWindow.waitForSpace(maxWaitTimeout); if (traceEnabled) { log.trace("write({}) len={} - available={}", this, l, available);