This is an automated email from the ASF dual-hosted git repository. lgoldstein pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/mina-sshd.git
commit daf1bd306d866bfce58516e2225a90ac0f256177 Author: Lyor Goldstein <lgoldst...@apache.org> AuthorDate: Thu Oct 3 13:29:55 2019 +0300 Truncated some long code lines --- .../sshd/common/future/AbstractSshFuture.java | 27 +- .../common/future/DefaultVerifiableSshFuture.java | 4 +- .../sshd/agent/local/AgentForwardedChannel.java | 16 +- .../sshd/agent/local/ChannelAgentForwarding.java | 15 +- .../sshd/agent/unix/ChannelAgentForwarding.java | 12 +- .../java/org/apache/sshd/client/SshClient.java | 65 ++-- .../sshd/client/channel/ChannelDirectTcpip.java | 10 +- .../apache/sshd/client/channel/ChannelSession.java | 15 +- .../sshd/client/channel/ChannelSubsystem.java | 5 +- .../client/channel/PtyCapableChannelSession.java | 9 +- .../sshd/client/future/DefaultAuthFuture.java | 5 +- .../sshd/client/future/DefaultOpenFuture.java | 5 +- .../sshd/common/channel/AbstractChannel.java | 13 +- .../common/channel/ChannelAsyncInputStream.java | 5 +- .../sshd/common/forward/TcpipClientChannel.java | 10 +- .../common/future/DefaultKeyExchangeFuture.java | 9 +- .../common/helpers/AbstractFactoryManager.java | 19 +- .../sshd/common/io/AbstractIoWriteFuture.java | 9 +- .../java/org/apache/sshd/server/SshServer.java | 16 +- .../sshd/server/channel/AbstractServerChannel.java | 16 +- .../apache/sshd/server/channel/ChannelSession.java | 87 +++-- .../sshd/server/forward/TcpipServerChannel.java | 27 +- .../sshd/server/session/AbstractServerSession.java | 37 ++- .../sshd/server/session/ServerSessionImpl.java | 3 +- .../sshd/server/x11/ChannelForwardedX11.java | 13 +- .../sftp/AbstractSftpSubsystemHelper.java | 350 ++++++++++++++------- .../sshd/server/subsystem/sftp/SftpSubsystem.java | 68 ++-- 27 files changed, 602 insertions(+), 268 deletions(-) diff --git a/sshd-common/src/main/java/org/apache/sshd/common/future/AbstractSshFuture.java b/sshd-common/src/main/java/org/apache/sshd/common/future/AbstractSshFuture.java index e727560..bedfd57 100644 --- a/sshd-common/src/main/java/org/apache/sshd/common/future/AbstractSshFuture.java +++ b/sshd-common/src/main/java/org/apache/sshd/common/future/AbstractSshFuture.java @@ -66,9 +66,10 @@ public abstract class AbstractSshFuture<T extends SshFuture> extends AbstractLog try { return await0(timeoutMillis, false) != null; } catch (InterruptedIOException e) { - throw formatExceptionMessage(msg -> new InternalError(msg, e), - "Unexpected interrupted exception wile awaitUninterruptibly %d msec: %s", - timeoutMillis, e.getMessage()); + throw formatExceptionMessage( + msg -> new InternalError(msg, e), + "Unexpected interrupted exception wile awaitUninterruptibly %d msec: %s", + timeoutMillis, e.getMessage()); } } @@ -109,7 +110,10 @@ public abstract class AbstractSshFuture<T extends SshFuture> extends AbstractLog protected <R> R verifyResult(Class<? extends R> expectedType, long timeout) throws IOException { Object value = await0(timeout, true); if (value == null) { - throw formatExceptionMessage(SshException::new, "Failed to get operation result within specified timeout: %s", timeout); + throw formatExceptionMessage( + SshException::new, + "Failed to get operation result within specified timeout: %s", + timeout); } Class<?> actualType = value.getClass(); @@ -129,9 +133,13 @@ public abstract class AbstractSshFuture<T extends SshFuture> extends AbstractLog } Throwable cause = GenericUtils.resolveExceptionCause(t); - throw formatExceptionMessage(msg -> new SshException(msg, cause), "Failed (%s) to execute: %s", t.getClass().getSimpleName(), t.getMessage()); + throw formatExceptionMessage( + msg -> new SshException(msg, cause), + "Failed (%s) to execute: %s", + t.getClass().getSimpleName(), t.getMessage()); } else { // what else can it be ???? - throw formatExceptionMessage(StreamCorruptedException::new, "Unknown result type: %s", actualType.getName()); + throw formatExceptionMessage( + StreamCorruptedException::new, "Unknown result type: %s", actualType.getName()); } } @@ -172,8 +180,8 @@ public abstract class AbstractSshFuture<T extends SshFuture> extends AbstractLog } /** - * Generates an exception whose message is prefixed by the future simple class name + {@link #getId() identifier} - * as a hint to the context of the failure. + * Generates an exception whose message is prefixed by the future simple + * class name + {@link #getId() identifier} as a hint to the context of the failure. * * @param <E> Type of {@link Throwable} being generated * @param exceptionCreator The exception creator from the formatted message @@ -181,7 +189,8 @@ public abstract class AbstractSshFuture<T extends SshFuture> extends AbstractLog * @param args The formatting arguments * @return The generated exception */ - protected <E extends Throwable> E formatExceptionMessage(Function<? super String, ? extends E> exceptionCreator, String format, Object... args) { + protected <E extends Throwable> E formatExceptionMessage( + Function<? super String, ? extends E> exceptionCreator, String format, Object... args) { String messagePayload = String.format(format, args); String excMessage = getClass().getSimpleName() + "[" + getId() + "]: " + messagePayload; return exceptionCreator.apply(excMessage); diff --git a/sshd-common/src/main/java/org/apache/sshd/common/future/DefaultVerifiableSshFuture.java b/sshd-common/src/main/java/org/apache/sshd/common/future/DefaultVerifiableSshFuture.java index 1b02fed..b358b0e 100644 --- a/sshd-common/src/main/java/org/apache/sshd/common/future/DefaultVerifiableSshFuture.java +++ b/sshd-common/src/main/java/org/apache/sshd/common/future/DefaultVerifiableSshFuture.java @@ -23,7 +23,9 @@ package org.apache.sshd.common.future; * @param <T> Type of future * @author <a href="mailto:d...@mina.apache.org">Apache MINA SSHD Project</a> */ -public abstract class DefaultVerifiableSshFuture<T extends SshFuture> extends DefaultSshFuture<T> implements VerifiableFuture<T> { +public abstract class DefaultVerifiableSshFuture<T extends SshFuture> + extends DefaultSshFuture<T> + implements VerifiableFuture<T> { protected DefaultVerifiableSshFuture(Object id, Object lock) { super(id, lock); } diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/local/AgentForwardedChannel.java b/sshd-core/src/main/java/org/apache/sshd/agent/local/AgentForwardedChannel.java index 4dd8f8e..5e8eb37 100644 --- a/sshd-core/src/main/java/org/apache/sshd/agent/local/AgentForwardedChannel.java +++ b/sshd-core/src/main/java/org/apache/sshd/agent/local/AgentForwardedChannel.java @@ -87,7 +87,8 @@ public class AgentForwardedChannel extends AbstractClientChannel { } }; - String chType = PropertyResolverUtils.getString(getSession(), FactoryManager.AGENT_FORWARDING_TYPE); + String chType = PropertyResolverUtils.getString( + getSession(), FactoryManager.AGENT_FORWARDING_TYPE); rtn.setChannelType(chType); return rtn; } @@ -131,20 +132,25 @@ public class AgentForwardedChannel extends AbstractClientChannel { try { messages.wait(idleTimeout); } catch (InterruptedException e) { - throw (IOException) new InterruptedIOException("Interrupted while waiting for messages at iteration #" + count).initCause(e); + throw (IOException) new InterruptedIOException( + "Interrupted while waiting for messages at iteration #" + count) + .initCause(e); } } } @Override protected void doOpen() throws IOException { - ValidateUtils.checkTrue(!Streaming.Async.equals(streaming), "Asynchronous streaming isn't supported yet on this channel"); - invertedIn = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + ValidateUtils.checkTrue( + !Streaming.Async.equals(streaming), "Asynchronous streaming isn't supported yet on this channel"); + invertedIn = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); } @Override protected void doWriteData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); Buffer message = null; synchronized (receiveBuffer) { diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/local/ChannelAgentForwarding.java b/sshd-core/src/main/java/org/apache/sshd/agent/local/ChannelAgentForwarding.java index d43e613..64ac4bc 100644 --- a/sshd-core/src/main/java/org/apache/sshd/agent/local/ChannelAgentForwarding.java +++ b/sshd-core/src/main/java/org/apache/sshd/agent/local/ChannelAgentForwarding.java @@ -57,11 +57,14 @@ public class ChannelAgentForwarding extends AbstractServerChannel { OpenFuture f = new DefaultOpenFuture(this, this); String changeEvent = "auth-agent"; try { - out = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + out = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); Session session = getSession(); - FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager"); - SshAgentFactory factory = Objects.requireNonNull(manager.getAgentFactory(), "No agent factory"); + FactoryManager manager = + Objects.requireNonNull(session.getFactoryManager(), "No factory manager"); + SshAgentFactory factory = + Objects.requireNonNull(manager.getAgentFactory(), "No agent factory"); agent = factory.createClient(manager); client = new AgentClient(); @@ -119,13 +122,15 @@ public class ChannelAgentForwarding extends AbstractServerChannel { @Override protected void doWriteData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); client.messageReceived(new ByteArrayBuffer(data, off, (int) len)); } @Override protected void doWriteExtendedData(byte[] data, int off, long len) throws IOException { - throw new UnsupportedOperationException("AgentForward channel does not support extended data"); + throw new UnsupportedOperationException( + "AgentForward channel does not support extended data"); } @SuppressWarnings("synthetic-access") diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/unix/ChannelAgentForwarding.java b/sshd-core/src/main/java/org/apache/sshd/agent/unix/ChannelAgentForwarding.java index 073c978..4816e0f 100644 --- a/sshd-core/src/main/java/org/apache/sshd/agent/unix/ChannelAgentForwarding.java +++ b/sshd-core/src/main/java/org/apache/sshd/agent/unix/ChannelAgentForwarding.java @@ -88,8 +88,10 @@ public class ChannelAgentForwarding extends AbstractServerChannel { : ThreadUtils.noClose(service); int copyBufSize = this.getIntProperty(FORWARDER_BUFFER_SIZE, DEFAULT_FORWARDER_BUF_SIZE); - ValidateUtils.checkTrue(copyBufSize >= MIN_FORWARDER_BUF_SIZE, "Copy buf size below min.: %d", copyBufSize); - ValidateUtils.checkTrue(copyBufSize <= MAX_FORWARDER_BUF_SIZE, "Copy buf size above max.: %d", copyBufSize); + ValidateUtils.checkTrue(copyBufSize >= MIN_FORWARDER_BUF_SIZE, + "Copy buf size below min.: %d", copyBufSize); + ValidateUtils.checkTrue(copyBufSize <= MAX_FORWARDER_BUF_SIZE, + "Copy buf size above max.: %d", copyBufSize); forwarder = forwardService.submit(() -> { try { @@ -158,7 +160,8 @@ public class ChannelAgentForwarding extends AbstractServerChannel { @Override protected void doWriteData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); int result = Socket.send(handle, data, off, (int) len); if (result < Status.APR_SUCCESS) { throwException(result); @@ -167,7 +170,8 @@ public class ChannelAgentForwarding extends AbstractServerChannel { @Override protected void doWriteExtendedData(byte[] data, int off, long len) throws IOException { - throw new UnsupportedOperationException("AgentForward channel does not support extended data"); + throw new UnsupportedOperationException( + "AgentForward channel does not support extended data"); } /** diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java index f9dbaf4..477d7c7 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java @@ -214,7 +214,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa @Override public void setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier) { - this.serverKeyVerifier = Objects.requireNonNull(serverKeyVerifier, "No server key verifier"); + this.serverKeyVerifier = + Objects.requireNonNull(serverKeyVerifier, "No server key verifier"); } @Override @@ -224,7 +225,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa @Override public void setHostConfigEntryResolver(HostConfigEntryResolver resolver) { - this.hostConfigEntryResolver = Objects.requireNonNull(resolver, "No host configuration entry resolver"); + this.hostConfigEntryResolver = + Objects.requireNonNull(resolver, "No host configuration entry resolver"); } @Override @@ -234,7 +236,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa @Override public void setFilePasswordProvider(FilePasswordProvider provider) { - this.filePasswordProvider = Objects.requireNonNull(provider, "No file password provider"); + this.filePasswordProvider = + Objects.requireNonNull(provider, "No file password provider"); } @Override @@ -244,7 +247,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa @Override public void setClientIdentityLoader(ClientIdentityLoader loader) { - this.clientIdentityLoader = Objects.requireNonNull(loader, "No client identity loader"); + this.clientIdentityLoader = + Objects.requireNonNull(loader, "No client identity loader"); } @Override @@ -300,7 +304,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa } int index = AuthenticationIdentitiesProvider.findIdentityIndex( - identities, AuthenticationIdentitiesProvider.PASSWORD_IDENTITY_COMPARATOR, password); + identities, AuthenticationIdentitiesProvider.PASSWORD_IDENTITY_COMPARATOR, password); if (index >= 0) { return (String) identities.remove(index); } else { @@ -317,7 +321,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa identities.add(kp); if (log.isDebugEnabled()) { - log.debug("addPublicKeyIdentity({}) {}", this, KeyUtils.getFingerPrint(kp.getPublic())); + log.debug("addPublicKeyIdentity({}) {}", + this, KeyUtils.getFingerPrint(kp.getPublic())); } } @@ -328,7 +333,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa } int index = AuthenticationIdentitiesProvider.findIdentityIndex( - identities, AuthenticationIdentitiesProvider.KEYPAIR_IDENTITY_COMPARATOR, kp); + identities, AuthenticationIdentitiesProvider.KEYPAIR_IDENTITY_COMPARATOR, kp); if (index >= 0) { return (KeyPair) identities.remove(index); } else { @@ -359,7 +364,10 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa // if no client identities override use the default KeyIdentityProvider defaultIdentities = getKeyIdentityProvider(); if (defaultIdentities == null) { - setKeyIdentityProvider(new DefaultClientIdentitiesWatcher(this::getClientIdentityLoader, this::getFilePasswordProvider)); + KeyIdentityProvider idsWatcher = + new DefaultClientIdentitiesWatcher( + this::getClientIdentityLoader, this::getFilePasswordProvider); + setKeyIdentityProvider(idsWatcher); } // Register the additional agent forwarding channel if needed @@ -430,7 +438,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa long maxWait = this.getLongProperty(STOP_WAIT_TIME, DEFAULT_STOP_WAIT_TIME); boolean successful = close(true).await(maxWait); if (!successful) { - throw new SocketTimeoutException("Failed to receive closure confirmation within " + maxWait + " millis"); + throw new SocketTimeoutException( + "Failed to receive closure confirmation within " + maxWait + " millis"); } } catch (IOException e) { if (log.isDebugEnabled()) { @@ -475,7 +484,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa String username, String host, int port, AttributeRepository context, SocketAddress localAddress) throws IOException { HostConfigEntryResolver resolver = getHostConfigEntryResolver(); - HostConfigEntry entry = resolver.resolveEffectiveHost(host, port, localAddress, username, context); + HostConfigEntry entry = + resolver.resolveEffectiveHost(host, port, localAddress, username, context); if (entry == null) { // generate a synthetic entry if (log.isDebugEnabled()) { @@ -510,13 +520,15 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa ValidateUtils.checkTrue(port > 0, "Invalid port: %d", port); HostConfigEntryResolver resolver = getHostConfigEntryResolver(); - HostConfigEntry entry = resolver.resolveEffectiveHost(host, port, localAddress, username, context); + HostConfigEntry entry = + resolver.resolveEffectiveHost(host, port, localAddress, username, context); if (entry == null) { if (log.isDebugEnabled()) { log.debug("connect({}@{}:{}) no overrides", username, host, port); } - return doConnect(username, targetAddress, context, localAddress, KeyIdentityProvider.EMPTY_KEYS_PROVIDER, true); + return doConnect( + username, targetAddress, context, localAddress, KeyIdentityProvider.EMPTY_KEYS_PROVIDER, true); } else { if (log.isDebugEnabled()) { log.debug("connect({}@{}:{}) effective: {}", username, host, port, entry); @@ -526,9 +538,11 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa } } else { if (log.isDebugEnabled()) { - log.debug("connect({}@{}) not an InetSocketAddress: {}", username, targetAddress, targetAddress.getClass().getName()); + log.debug("connect({}@{}) not an InetSocketAddress: {}", + username, targetAddress, targetAddress.getClass().getName()); } - return doConnect(username, targetAddress, context, localAddress, KeyIdentityProvider.EMPTY_KEYS_PROVIDER, true); + return doConnect( + username, targetAddress, context, localAddress, KeyIdentityProvider.EMPTY_KEYS_PROVIDER, true); } } @@ -553,7 +567,9 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa context, localAddress, keys, !hostConfig.isIdentitiesOnly()); } - protected KeyIdentityProvider preloadClientIdentities(Collection<? extends NamedResource> locations) throws IOException { + protected KeyIdentityProvider preloadClientIdentities( + Collection<? extends NamedResource> locations) + throws IOException { return GenericUtils.isEmpty(locations) ? KeyIdentityProvider.EMPTY_KEYS_PROVIDER : ClientIdentityLoader.asKeyIdentityProvider( @@ -568,14 +584,16 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa KeyIdentityProvider identities, boolean useDefaultIdentities) throws IOException { if (connector == null) { - throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server"); + throw new IllegalStateException( + "SshClient not started. Please call start() method before connecting to a server"); } ConnectFuture connectFuture = new DefaultConnectFuture(username + "@" + targetAddress, null); SshFutureListener<IoConnectFuture> listener = createConnectCompletionListener( connectFuture, username, targetAddress, identities, useDefaultIdentities); - IoConnectFuture connectingFuture = connector.connect(targetAddress, context, localAddress); + IoConnectFuture connectingFuture = + connector.connect(targetAddress, context, localAddress); connectingFuture.addListener(listener); return connectFuture; } @@ -633,13 +651,17 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa if (useDefaultIdentities) { setupDefaultSessionIdentities(session, identities); } else { - session.setKeyIdentityProvider((identities == null) ? KeyIdentityProvider.EMPTY_KEYS_PROVIDER : identities); + session.setKeyIdentityProvider( + (identities == null) + ? KeyIdentityProvider.EMPTY_KEYS_PROVIDER + : identities); } connectFuture.setSession(session); } - protected void setupDefaultSessionIdentities(ClientSession session, KeyIdentityProvider extraIdentities) { + protected void setupDefaultSessionIdentities( + ClientSession session, KeyIdentityProvider extraIdentities) { boolean debugEnabled = log.isDebugEnabled(); // check if session listener intervened KeyIdentityProvider kpSession = session.getKeyIdentityProvider(); @@ -728,7 +750,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa * @return The {@link SimpleClient} wrapper. <B>Note:</B> when the * wrapper is closed the client is also stopped */ - public static SimpleClient wrapAsSimpleClient(final SshClient client) { + public static SimpleClient wrapAsSimpleClient(SshClient client) { Objects.requireNonNull(client, "No client instance"); // wrap the client so that close() is also stop() final java.nio.channels.Channel channel = new java.nio.channels.Channel() { @@ -797,7 +819,8 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa public static <C extends SshClient> C setKeyPairProvider( C client, boolean strict, boolean supportedOnly, FilePasswordProvider provider, LinkOption... options) throws IOException, GeneralSecurityException { - return setKeyPairProvider(client, PublicKeyEntry.getDefaultKeysFolderPath(), strict, supportedOnly, provider, options); + return setKeyPairProvider( + client, PublicKeyEntry.getDefaultKeysFolderPath(), strict, supportedOnly, provider, options); } /** diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelDirectTcpip.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelDirectTcpip.java index 55ffcb8..8659e1f 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelDirectTcpip.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelDirectTcpip.java @@ -101,9 +101,12 @@ public class ChannelDirectTcpip extends AbstractClientChannel { asyncIn = new ChannelAsyncOutputStream(this, SshConstants.SSH_MSG_CHANNEL_DATA); asyncOut = new ChannelAsyncInputStream(this); } else { - out = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + out = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); invertedIn = out; - ChannelPipedInputStream pis = new ChannelPipedInputStream(this, getLocalWindow()); + + ChannelPipedInputStream pis = + new ChannelPipedInputStream(this, getLocalWindow()); pipe = new ChannelPipedOutputStream(pis); in = pis; invertedOut = in; @@ -112,7 +115,8 @@ public class ChannelDirectTcpip extends AbstractClientChannel { @Override protected void doWriteData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); pipe.write(data, off, (int) len); pipe.flush(); diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSession.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSession.java index 79258fb..dfe7f40 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSession.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSession.java @@ -71,7 +71,8 @@ public class ChannelSession extends AbstractClientChannel { asyncOut = new ChannelAsyncInputStream(this); asyncErr = new ChannelAsyncInputStream(this); } else { - invertedIn = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + invertedIn = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); Window wLocal = getLocalWindow(); if (out == null) { @@ -91,7 +92,8 @@ public class ChannelSession extends AbstractClientChannel { // allocate a temporary executor service if none provided CloseableExecutorService service = getExecutorService(); if (service == null) { - pumperService = ThreadUtils.newSingleThreadExecutor("ClientInputStreamPump[" + this.toString() + "]"); + pumperService = ThreadUtils.newSingleThreadExecutor( + "ClientInputStreamPump[" + this.toString() + "]"); } else { pumperService = ThreadUtils.noClose(service); } @@ -105,7 +107,8 @@ public class ChannelSession extends AbstractClientChannel { } @Override - protected RequestHandler.Result handleInternalRequest(String req, boolean wantReply, Buffer buffer) throws IOException { + protected RequestHandler.Result handleInternalRequest(String req, boolean wantReply, Buffer buffer) + throws IOException { switch (req) { case "xon-xoff": return handleXonXoff(buffer, wantReply); @@ -161,7 +164,8 @@ public class ChannelSession extends AbstractClientChannel { Session session = getSession(); Window wRemote = getRemoteWindow(); long packetSize = wRemote.getPacketSize(); - ValidateUtils.checkTrue(packetSize < Integer.MAX_VALUE, "Remote packet size exceeds int boundary: %d", packetSize); + ValidateUtils.checkTrue(packetSize < Integer.MAX_VALUE, + "Remote packet size exceeds int boundary: %d", packetSize); byte[] buffer = new byte[(int) packetSize]; while (!closeFuture.isClosed()) { int len = securedRead(in, buffer, 0, buffer.length); @@ -186,7 +190,8 @@ public class ChannelSession extends AbstractClientChannel { } catch (Exception e) { if (!isClosing()) { if (log.isDebugEnabled()) { - log.debug("pumpInputStream({}) Caught {} : {}", this, e.getClass().getSimpleName(), e.getMessage()); + log.debug("pumpInputStream({}) Caught {} : {}", + this, e.getClass().getSimpleName(), e.getMessage()); } if (log.isTraceEnabled()) { log.trace("pumpInputStream(" + this + ") caught exception details", e); diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSubsystem.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSubsystem.java index 7b30e89..b9076f0 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSubsystem.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSubsystem.java @@ -76,9 +76,10 @@ public class ChannelSubsystem extends ChannelSession { } Session session = getSession(); - boolean wantReply = this.getBooleanProperty(REQUEST_SUBSYSTEM_REPLY, DEFAULT_REQUEST_SUBSYSTEM_REPLY); + boolean wantReply = this.getBooleanProperty( + REQUEST_SUBSYSTEM_REPLY, DEFAULT_REQUEST_SUBSYSTEM_REPLY); Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_REQUEST, - Channel.CHANNEL_SUBSYSTEM.length() + systemName.length() + Integer.SIZE); + Channel.CHANNEL_SUBSYSTEM.length() + systemName.length() + Integer.SIZE); buffer.putInt(getRecipient()); buffer.putString(Channel.CHANNEL_SUBSYSTEM); buffer.putBoolean(wantReply); diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/PtyCapableChannelSession.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/PtyCapableChannelSession.java index c42eae3..b091d0a 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/channel/PtyCapableChannelSession.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/PtyCapableChannelSession.java @@ -82,7 +82,8 @@ public class PtyCapableChannelSession extends ChannelSession implements PtyChann private final Map<String, Object> env = new LinkedHashMap<>(); private final PtyChannelConfiguration config; - public PtyCapableChannelSession(boolean usePty, PtyChannelConfigurationHolder configHolder, Map<String, ?> env) { + public PtyCapableChannelSession( + boolean usePty, PtyChannelConfigurationHolder configHolder, Map<String, ?> env) { this.usePty = usePty; this.config = PtyChannelConfigurationMutator.copyConfiguration( configHolder, new PtyChannelConfiguration()); @@ -251,7 +252,8 @@ public class PtyCapableChannelSession extends ChannelSession implements PtyChann String channelType = session.getStringProperty( SshAgentFactory.PROXY_AUTH_CHANNEL_TYPE, SshAgentFactory.DEFAULT_PROXY_AUTH_CHANNEL_TYPE); - Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_REQUEST, Long.SIZE); + Buffer buffer = session.createBuffer( + SshConstants.SSH_MSG_CHANNEL_REQUEST, Long.SIZE); buffer.putInt(getRecipient()); buffer.putString(channelType); buffer.putBoolean(false); // want-reply @@ -263,7 +265,8 @@ public class PtyCapableChannelSession extends ChannelSession implements PtyChann log.debug("doOpenPty({}) Send SSH_MSG_CHANNEL_REQUEST pty-req: {}", this, config); } - Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_REQUEST, Byte.MAX_VALUE); + Buffer buffer = session.createBuffer( + SshConstants.SSH_MSG_CHANNEL_REQUEST, Byte.MAX_VALUE); buffer.putInt(getRecipient()); buffer.putString("pty-req"); buffer.putBoolean(false); // want-reply diff --git a/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultAuthFuture.java b/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultAuthFuture.java index 36b8ada..a392a5a 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultAuthFuture.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultAuthFuture.java @@ -38,7 +38,10 @@ public class DefaultAuthFuture extends DefaultVerifiableSshFuture<AuthFuture> im public AuthFuture verify(long timeoutMillis) throws IOException { Boolean result = verifyResult(Boolean.class, timeoutMillis); if (!result) { - throw formatExceptionMessage(SshException::new, "Authentication failed while waiting %d msec.", timeoutMillis); + throw formatExceptionMessage( + SshException::new, + "Authentication failed while waiting %d msec.", + timeoutMillis); } return this; diff --git a/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultOpenFuture.java b/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultOpenFuture.java index 550a50b..a081025 100644 --- a/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultOpenFuture.java +++ b/sshd-core/src/main/java/org/apache/sshd/client/future/DefaultOpenFuture.java @@ -38,7 +38,10 @@ public class DefaultOpenFuture extends DefaultVerifiableSshFuture<OpenFuture> im public OpenFuture verify(long timeoutMillis) throws IOException { Boolean result = verifyResult(Boolean.class, timeoutMillis); if (!result) { - throw formatExceptionMessage(SshException::new, "Channel opening failed while waiting %d msec.", timeoutMillis); + throw formatExceptionMessage( + SshException::new, + "Channel opening failed while waiting %d msec.", + timeoutMillis); } return this; diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/AbstractChannel.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/AbstractChannel.java index fd0a001..a5b788e 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/channel/AbstractChannel.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/AbstractChannel.java @@ -309,7 +309,8 @@ public abstract class AbstractChannel * @throws IOException If failed to send the response (if needed) * @see #handleInternalRequest(String, boolean, Buffer) */ - protected void handleUnknownChannelRequest(String req, boolean wantReply, Buffer buffer) throws IOException { + protected void handleUnknownChannelRequest(String req, boolean wantReply, Buffer buffer) + throws IOException { RequestHandler.Result r = handleInternalRequest(req, wantReply, buffer); if ((r == null) || RequestHandler.Result.Unsupported.equals(r)) { log.warn("handleUnknownChannelRequest({}) Unknown channel request: {}[want-reply={}]", this, req, wantReply); @@ -331,14 +332,17 @@ public abstract class AbstractChannel * and reply is required then a failure message will be sent * @throws IOException If failed to process the request internally */ - protected RequestHandler.Result handleInternalRequest(String req, boolean wantReply, Buffer buffer) throws IOException { + protected RequestHandler.Result handleInternalRequest(String req, boolean wantReply, Buffer buffer) + throws IOException { if (log.isDebugEnabled()) { log.debug("handleInternalRequest({})[want-reply={}] unknown type: {}", this, wantReply, req); } return RequestHandler.Result.Unsupported; } - protected IoWriteFuture sendResponse(Buffer buffer, String req, RequestHandler.Result result, boolean wantReply) throws IOException { + protected IoWriteFuture sendResponse( + Buffer buffer, String req, RequestHandler.Result result, boolean wantReply) + throws IOException { if (log.isDebugEnabled()) { log.debug("sendResponse({}) request={} result={}, want-reply={}", this, req, result, wantReply); } @@ -970,7 +974,8 @@ public abstract class AbstractChannel @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T computeAttributeIfAbsent( - AttributeRepository.AttributeKey<T> key, Function<? super AttributeRepository.AttributeKey<T>, ? extends T> resolver) { + AttributeRepository.AttributeKey<T> key, + Function<? super AttributeRepository.AttributeKey<T>, ? extends T> resolver) { return (T) attributes.computeIfAbsent(Objects.requireNonNull(key, "No key"), (Function) resolver); } diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncInputStream.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncInputStream.java index ee79c84..741f0ad 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncInputStream.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncInputStream.java @@ -189,7 +189,10 @@ public class ChannelAsyncInputStream extends AbstractCloseable implements IoInpu } else if (v instanceof Number) { return ((Number) v).intValue(); } else { - throw formatExceptionMessage(IllegalStateException::new, "Unknown read value type: %s", (v == null) ? "null" : v.getClass().getName()); + throw formatExceptionMessage( + IllegalStateException::new, + "Unknown read value type: %s", + (v == null) ? "null" : v.getClass().getName()); } } diff --git a/sshd-core/src/main/java/org/apache/sshd/common/forward/TcpipClientChannel.java b/sshd-core/src/main/java/org/apache/sshd/common/forward/TcpipClientChannel.java index b83393b..ac1d6ab 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/forward/TcpipClientChannel.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/forward/TcpipClientChannel.java @@ -165,7 +165,9 @@ public class TcpipClientChannel extends AbstractClientChannel implements Forward if (streaming == Streaming.Async) { throw new IllegalArgumentException("Asynchronous streaming isn't supported yet on this channel"); } - out = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + + out = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); invertedIn = out; } @@ -194,7 +196,8 @@ public class TcpipClientChannel extends AbstractClientChannel implements Forward @Override protected synchronized void doWriteData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); // Make sure we copy the data as the incoming buffer may be reused Buffer buf = ByteArrayBuffer.getCompactClone(data, off, (int) len); Window wLocal = getLocalWindow(); @@ -204,7 +207,8 @@ public class TcpipClientChannel extends AbstractClientChannel implements Forward @Override protected void doWriteExtendedData(byte[] data, int off, long len) throws IOException { - throw new UnsupportedOperationException(getChannelType() + "Tcpip channel does not support extended data"); + throw new UnsupportedOperationException( + getChannelType() + "Tcpip channel does not support extended data"); } @Override diff --git a/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultKeyExchangeFuture.java b/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultKeyExchangeFuture.java index a4ae41e..060bec9 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultKeyExchangeFuture.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultKeyExchangeFuture.java @@ -26,7 +26,9 @@ import org.apache.sshd.common.SshException; /** * @author <a href="mailto:d...@mina.apache.org">Apache MINA SSHD Project</a> */ -public class DefaultKeyExchangeFuture extends DefaultVerifiableSshFuture<KeyExchangeFuture> implements KeyExchangeFuture { +public class DefaultKeyExchangeFuture + extends DefaultVerifiableSshFuture<KeyExchangeFuture> + implements KeyExchangeFuture { public DefaultKeyExchangeFuture(Object id, Object lock) { super(id, lock); } @@ -35,7 +37,10 @@ public class DefaultKeyExchangeFuture extends DefaultVerifiableSshFuture<KeyExch public KeyExchangeFuture verify(long timeoutMillis) throws IOException { Boolean result = verifyResult(Boolean.class, timeoutMillis); if (!result) { - throw formatExceptionMessage(SshException::new, "Key exchange failed while waiting %d msec.", timeoutMillis); + throw formatExceptionMessage( + SshException::new, + "Key exchange failed while waiting %d msec.", + timeoutMillis); } return this; diff --git a/sshd-core/src/main/java/org/apache/sshd/common/helpers/AbstractFactoryManager.java b/sshd-core/src/main/java/org/apache/sshd/common/helpers/AbstractFactoryManager.java index 86c1963..65306eb 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/helpers/AbstractFactoryManager.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/helpers/AbstractFactoryManager.java @@ -101,9 +101,12 @@ public abstract class AbstractFactoryManager extends AbstractKexFactoryManager i protected AbstractFactoryManager() { ClassLoader loader = getClass().getClassLoader(); - sessionListenerProxy = EventListenerUtils.proxyWrapper(SessionListener.class, loader, sessionListeners); - channelListenerProxy = EventListenerUtils.proxyWrapper(ChannelListener.class, loader, channelListeners); - tunnelListenerProxy = EventListenerUtils.proxyWrapper(PortForwardingEventListener.class, loader, tunnelListeners); + sessionListenerProxy = + EventListenerUtils.proxyWrapper(SessionListener.class, loader, sessionListeners); + channelListenerProxy = + EventListenerUtils.proxyWrapper(ChannelListener.class, loader, channelListeners); + tunnelListenerProxy = + EventListenerUtils.proxyWrapper(PortForwardingEventListener.class, loader, tunnelListeners); } @Override @@ -167,7 +170,8 @@ public abstract class AbstractFactoryManager extends AbstractKexFactoryManager i @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T computeAttributeIfAbsent( - AttributeRepository.AttributeKey<T> key, Function<? super AttributeRepository.AttributeKey<T>, ? extends T> resolver) { + AttributeRepository.AttributeKey<T> key, + Function<? super AttributeRepository.AttributeKey<T>, ? extends T> resolver) { return (T) attributes.computeIfAbsent(Objects.requireNonNull(key, "No key"), (Function) resolver); } @@ -202,7 +206,8 @@ public abstract class AbstractFactoryManager extends AbstractKexFactoryManager i @Override public String getVersion() { String version = PropertyResolverUtils.getStringProperty( - VersionProperties.getVersionProperties(), VersionProperties.REPORTED_VERSION, DEFAULT_VERSION); + VersionProperties.getVersionProperties(), + VersionProperties.REPORTED_VERSION, DEFAULT_VERSION); return version.toUpperCase(); } @@ -532,7 +537,9 @@ public abstract class AbstractFactoryManager extends AbstractKexFactoryManager i Objects.requireNonNull(getRandomFactory(), "RandomFactory not set"); if (getIoServiceFactoryFactory() == null) { - setIoServiceFactoryFactory(DefaultIoServiceFactoryFactory.getDefaultIoServiceFactoryFactoryInstance()); + IoServiceFactoryFactory defaultFactory = + DefaultIoServiceFactoryFactory.getDefaultIoServiceFactoryFactoryInstance(); + setIoServiceFactoryFactory(defaultFactory); } } } diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java b/sshd-core/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java index 87ca963..0be8247 100644 --- a/sshd-core/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java +++ b/sshd-core/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java @@ -27,7 +27,9 @@ import org.apache.sshd.common.future.DefaultVerifiableSshFuture; /** * @author <a href="mailto:d...@mina.apache.org">Apache MINA SSHD Project</a> */ -public abstract class AbstractIoWriteFuture extends DefaultVerifiableSshFuture<IoWriteFuture> implements IoWriteFuture { +public abstract class AbstractIoWriteFuture + extends DefaultVerifiableSshFuture<IoWriteFuture> + implements IoWriteFuture { protected AbstractIoWriteFuture(Object id, Object lock) { super(id, lock); } @@ -36,7 +38,10 @@ public abstract class AbstractIoWriteFuture extends DefaultVerifiableSshFuture<I public IoWriteFuture verify(long timeout) throws IOException { Boolean result = verifyResult(Boolean.class, timeout); if (!result) { - throw formatExceptionMessage(SshException::new, "Write failed signalled while wait %d msec.", timeout); + throw formatExceptionMessage( + SshException::new, + "Write failed signalled while wait %d msec.", + timeout); } return this; diff --git a/sshd-core/src/main/java/org/apache/sshd/server/SshServer.java b/sshd-core/src/main/java/org/apache/sshd/server/SshServer.java index 7096d9f..fcc676f 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/SshServer.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/SshServer.java @@ -266,8 +266,10 @@ public class SshServer extends AbstractFactoryManager implements ServerFactoryMa ValidateUtils.checkTrue(getPort() >= 0 /* zero means not set yet */, "Bad port number: %d", Integer.valueOf(getPort())); - List<UserAuthFactory> authFactories = ServerAuthenticationManager.resolveUserAuthFactories(this); - setUserAuthFactories(ValidateUtils.checkNotNullAndNotEmpty(authFactories, "UserAuthFactories not set")); + List<UserAuthFactory> authFactories = + ServerAuthenticationManager.resolveUserAuthFactories(this); + setUserAuthFactories( + ValidateUtils.checkNotNullAndNotEmpty(authFactories, "UserAuthFactories not set")); ValidateUtils.checkNotNullAndNotEmpty(getChannelFactories(), "ChannelFactories not set"); Objects.requireNonNull(getKeyPairProvider(), "HostKeyProvider not set"); @@ -320,7 +322,8 @@ public class SshServer extends AbstractFactoryManager implements ServerFactoryMa acceptor.bind(new InetSocketAddress(inetAddress, port)); if (port == 0) { - SocketAddress selectedAddress = GenericUtils.head(acceptor.getBoundAddresses()); + SocketAddress selectedAddress = + GenericUtils.head(acceptor.getBoundAddresses()); port = ((InetSocketAddress) selectedAddress).getPort(); log.info("start() listen on auto-allocated port=" + port); } @@ -329,7 +332,8 @@ public class SshServer extends AbstractFactoryManager implements ServerFactoryMa } else { acceptor.bind(new InetSocketAddress(port)); if (port == 0) { - SocketAddress selectedAddress = GenericUtils.head(acceptor.getBoundAddresses()); + SocketAddress selectedAddress = + GenericUtils.head(acceptor.getBoundAddresses()); port = ((InetSocketAddress) selectedAddress).getPort(); log.info("start() listen on auto-allocated port=" + port); } @@ -352,7 +356,9 @@ public class SshServer extends AbstractFactoryManager implements ServerFactoryMa } try { - long maxWait = immediately ? this.getLongProperty(STOP_WAIT_TIME, DEFAULT_STOP_WAIT_TIME) : Long.MAX_VALUE; + long maxWait = immediately + ? this.getLongProperty(STOP_WAIT_TIME, DEFAULT_STOP_WAIT_TIME) + : Long.MAX_VALUE; boolean successful = close(immediately).await(maxWait); if (!successful) { throw new SocketTimeoutException("Failed to receive closure confirmation within " + maxWait + " millis"); diff --git a/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java b/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java index 4349e1b..aa42934 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java @@ -67,7 +67,8 @@ public abstract class AbstractServerChannel extends AbstractChannel implements S setRecipient(recipient); Session s = getSession(); - FactoryManager manager = Objects.requireNonNull(s.getFactoryManager(), "No factory manager"); + FactoryManager manager = + Objects.requireNonNull(s.getFactoryManager(), "No factory manager"); Window wRemote = getRemoteWindow(); wRemote.init(rwSize, packetSize, manager); configureWindow(); @@ -75,8 +76,11 @@ public abstract class AbstractServerChannel extends AbstractChannel implements S } @Override - public void handleOpenSuccess(int recipient, long rwSize, long packetSize, Buffer buffer) throws IOException { - throw new UnsupportedOperationException("handleOpenSuccess(" + recipient + "," + rwSize + "," + packetSize + ") N/A"); + public void handleOpenSuccess( + int recipient, long rwSize, long packetSize, Buffer buffer) + throws IOException { + throw new UnsupportedOperationException( + "handleOpenSuccess(" + recipient + "," + rwSize + "," + packetSize + ") N/A"); } @Override @@ -116,10 +120,12 @@ public abstract class AbstractServerChannel extends AbstractChannel implements S } Session session = getSession(); - Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_REQUEST, Long.SIZE); + Buffer buffer = session.createBuffer( + SshConstants.SSH_MSG_CHANNEL_REQUEST, Long.SIZE); buffer.putInt(getRecipient()); buffer.putString("exit-status"); - buffer.putBoolean(false); // want-reply - must be FALSE - see https://tools.ietf.org/html/rfc4254 section 6.10 + // want-reply - must be FALSE - see https://tools.ietf.org/html/rfc4254 section 6.10 + buffer.putBoolean(false); buffer.putInt(v); writePacket(buffer); notifyStateChanged("exit-status"); diff --git a/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java b/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java index 1987d5d..6c02cc2 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java @@ -186,14 +186,17 @@ public class ChannelSession extends AbstractServerChannel { ChannelSession channel = ChannelSession.this; long timeout = PropertyResolverUtils.getLongProperty(channel, - ServerFactoryManager.COMMAND_EXIT_TIMEOUT, ServerFactoryManager.DEFAULT_COMMAND_EXIT_TIMEOUT); + ServerFactoryManager.COMMAND_EXIT_TIMEOUT, + ServerFactoryManager.DEFAULT_COMMAND_EXIT_TIMEOUT); if (debugEnabled) { log.debug("Wait {} ms for shell to exit cleanly on {}", timeout, channel); } Session s = channel.getSession(); - FactoryManager manager = Objects.requireNonNull(s.getFactoryManager(), "No factory manager"); - ScheduledExecutorService scheduler = Objects.requireNonNull(manager.getScheduledExecutorService(), "No scheduling service"); + FactoryManager manager = + Objects.requireNonNull(s.getFactoryManager(), "No factory manager"); + ScheduledExecutorService scheduler = + Objects.requireNonNull(manager.getScheduledExecutorService(), "No scheduling service"); scheduler.schedule(task, timeout, TimeUnit.MILLISECONDS); commandExitFuture.addListener(future -> task.cancel()); } @@ -229,7 +232,9 @@ public class ChannelSession extends AbstractServerChannel { Throwable[] suppressed = e.getSuppressed(); if (GenericUtils.length(suppressed) > 0) { for (Throwable t : suppressed) { - log.trace("Suppressed " + t.getClass().getSimpleName() + ") while close immediately resource(s) of " + this + ": " + t.getMessage()); + log.trace("Suppressed " + t.getClass().getSimpleName() + ")" + + " while close immediately resource(s) of " + this + + ": " + t.getMessage()); } } } @@ -259,7 +264,8 @@ public class ChannelSession extends AbstractServerChannel { if (isClosing()) { return; } - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); int reqLen = (int) len; if (receiver != null) { @@ -269,7 +275,8 @@ public class ChannelSession extends AbstractServerChannel { wLocal.consumeAndCheck(r); } } else { - ValidateUtils.checkTrue(len <= (Integer.MAX_VALUE - Long.SIZE), "Temporary data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= (Integer.MAX_VALUE - Long.SIZE), + "Temporary data length exceeds int boundaries: %d", len); if (receiverBuffer == null) { receiverBuffer = new ByteArrayBuffer(reqLen + Long.SIZE, false); } @@ -279,7 +286,8 @@ public class ChannelSession extends AbstractServerChannel { @Override protected void doWriteExtendedData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= (Integer.MAX_VALUE - Long.SIZE), "Extended data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= (Integer.MAX_VALUE - Long.SIZE), + "Extended data length exceeds int boundaries: %d", len); if (extendedDataWriter != null) { extendedDataWriter.data(this, data, off, (int) len); @@ -287,7 +295,7 @@ public class ChannelSession extends AbstractServerChannel { } int reqSize = (int) len; - int maxBufSize = PropertyResolverUtils.getIntProperty(this, MAX_EXTDATA_BUFSIZE, DEFAULT_MAX_EXTDATA_BUFSIZE); + int maxBufSize = this.getIntProperty(MAX_EXTDATA_BUFSIZE, DEFAULT_MAX_EXTDATA_BUFSIZE); int curBufSize = (extendedDataBuffer == null) ? 0 : extendedDataBuffer.available(); int totalSize = curBufSize + reqSize; if (totalSize > maxBufSize) { @@ -305,7 +313,9 @@ public class ChannelSession extends AbstractServerChannel { } @Override - protected RequestHandler.Result handleInternalRequest(String requestType, boolean wantReply, Buffer buffer) throws IOException { + protected RequestHandler.Result handleInternalRequest( + String requestType, boolean wantReply, Buffer buffer) + throws IOException { switch (requestType) { case "env": return handleEnv(buffer, wantReply); @@ -320,7 +330,8 @@ public class ChannelSession extends AbstractServerChannel { case Channel.CHANNEL_SHELL: if (this.type == null) { RequestHandler.Result r = handleShell(requestType, buffer, wantReply); - if (RequestHandler.Result.ReplySuccess.equals(r) || RequestHandler.Result.Replied.equals(r)) { + if (RequestHandler.Result.ReplySuccess.equals(r) + || RequestHandler.Result.Replied.equals(r)) { this.type = requestType; } return r; @@ -334,7 +345,8 @@ public class ChannelSession extends AbstractServerChannel { case Channel.CHANNEL_EXEC: if (this.type == null) { RequestHandler.Result r = handleExec(requestType, buffer, wantReply); - if (RequestHandler.Result.ReplySuccess.equals(r) || RequestHandler.Result.Replied.equals(r)) { + if (RequestHandler.Result.ReplySuccess.equals(r) + || RequestHandler.Result.Replied.equals(r)) { this.type = requestType; } return r; @@ -348,7 +360,8 @@ public class ChannelSession extends AbstractServerChannel { case Channel.CHANNEL_SUBSYSTEM: if (this.type == null) { RequestHandler.Result r = handleSubsystem(requestType, buffer, wantReply); - if (RequestHandler.Result.ReplySuccess.equals(r) || RequestHandler.Result.Replied.equals(r)) { + if (RequestHandler.Result.ReplySuccess.equals(r) + || RequestHandler.Result.Replied.equals(r)) { this.type = requestType; } return r; @@ -370,7 +383,9 @@ public class ChannelSession extends AbstractServerChannel { } @Override - protected IoWriteFuture sendResponse(Buffer buffer, String req, Result result, boolean wantReply) throws IOException { + protected IoWriteFuture sendResponse( + Buffer buffer, String req, Result result, boolean wantReply) + throws IOException { IoWriteFuture future = super.sendResponse(buffer, req, result, wantReply); if (!RequestHandler.Result.ReplySuccess.equals(result)) { return future; @@ -397,7 +412,11 @@ public class ChannelSession extends AbstractServerChannel { return future; } - // TODO - consider if (Channel.CHANNEL_SHELL.equals(req) || Channel.CHANNEL_EXEC.equals(req) || Channel.CHANNEL_SUBSYSTEM.equals(req)) { + /* + * TODO - consider if (Channel.CHANNEL_SHELL.equals(req) + * || Channel.CHANNEL_EXEC.equals(req) + * || Channel.CHANNEL_SUBSYSTEM.equals(req)) { + */ if (log.isDebugEnabled()) { log.debug("sendResponse({}) request={} activate command", this, req); } @@ -466,7 +485,8 @@ public class ChannelSession extends AbstractServerChannel { int tWidth = buffer.getInt(); int tHeight = buffer.getInt(); if (log.isDebugEnabled()) { - log.debug("handleWindowChange({}): ({} - {}), ({}, {})", this, tColumns, tRows, tWidth, tHeight); + log.debug("handleWindowChange({}): ({} - {}), ({}, {})", + this, tColumns, tRows, tWidth, tHeight); } StandardEnvironment e = getEnvironment(); @@ -505,7 +525,9 @@ public class ChannelSession extends AbstractServerChannel { return RequestHandler.Result.ReplySuccess; } - protected RequestHandler.Result handleShell(String request, Buffer buffer, boolean wantReply) throws IOException { + protected RequestHandler.Result handleShell( + String request, Buffer buffer, boolean wantReply) + throws IOException { // If we're already closing, ignore incoming data if (isClosing()) { if (log.isDebugEnabled()) { @@ -514,9 +536,11 @@ public class ChannelSession extends AbstractServerChannel { return RequestHandler.Result.ReplyFailure; } - ServerSession shellSession = Objects.requireNonNull(getServerSession(), "No server session"); - ServerFactoryManager manager = shellSession.getFactoryManager(); - ShellFactory factory = Objects.requireNonNull(manager, "No server factory manager").getShellFactory(); + ServerSession shellSession = + Objects.requireNonNull(getServerSession(), "No server session"); + ServerFactoryManager manager = + Objects.requireNonNull(shellSession.getFactoryManager(), "No server factory manager"); + ShellFactory factory = manager.getShellFactory(); if (factory == null) { if (log.isDebugEnabled()) { log.debug("handleShell({}) - no shell factory", this); @@ -545,16 +569,20 @@ public class ChannelSession extends AbstractServerChannel { return prepareChannelCommand(request, commandInstance); } - protected RequestHandler.Result handleExec(String request, Buffer buffer, boolean wantReply) throws IOException { + protected RequestHandler.Result handleExec( + String request, Buffer buffer, boolean wantReply) + throws IOException { // If we're already closing, ignore incoming data if (isClosing()) { return RequestHandler.Result.ReplyFailure; } String commandLine = buffer.getString(); - ServerSession cmdSession = Objects.requireNonNull(getServerSession(), "No server session"); - ServerFactoryManager manager = cmdSession.getFactoryManager(); - CommandFactory factory = Objects.requireNonNull(manager, "No server factory manager").getCommandFactory(); + ServerSession cmdSession = + Objects.requireNonNull(getServerSession(), "No server session"); + ServerFactoryManager manager = + Objects.requireNonNull(cmdSession.getFactoryManager(), "No server factory manager"); + CommandFactory factory = manager.getCommandFactory(); if (factory == null) { log.warn("handleExec({}) No command factory for command: {}", this, commandLine); return RequestHandler.Result.ReplyFailure; @@ -585,7 +613,9 @@ public class ChannelSession extends AbstractServerChannel { return prepareChannelCommand(request, commandInstance); } - protected RequestHandler.Result handleSubsystem(String request, Buffer buffer, boolean wantReply) throws IOException { + protected RequestHandler.Result handleSubsystem( + String request, Buffer buffer, boolean wantReply) + throws IOException { String subsystem = buffer.getString(); if (log.isDebugEnabled()) { log.debug("handleSubsystem({})[want-reply={}] subsystem={}", this, wantReply, subsystem); @@ -710,8 +740,10 @@ public class ChannelSession extends AbstractServerChannel { ((AsyncCommand) command).setIoErrorStream(asyncErr); } else { Window wRemote = getRemoteWindow(); - out = new ChannelOutputStream(this, wRemote, log, SshConstants.SSH_MSG_CHANNEL_DATA, false); - err = new ChannelOutputStream(this, wRemote, log, SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA, false); + out = new ChannelOutputStream( + this, wRemote, log, SshConstants.SSH_MSG_CHANNEL_DATA, false); + err = new ChannelOutputStream( + this, wRemote, log, SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA, false); if (log.isTraceEnabled()) { // Wrap in logging filters out = new LoggingFilterOutputStream(out, "OUT(" + this + ")", log, this); @@ -777,7 +809,8 @@ public class ChannelSession extends AbstractServerChannel { String requestType, Buffer buffer, boolean wantReply) throws IOException { ServerSession session = getServerSession(); - PropertyResolverUtils.updateProperty(session, FactoryManager.AGENT_FORWARDING_TYPE, requestType); + PropertyResolverUtils.updateProperty( + session, FactoryManager.AGENT_FORWARDING_TYPE, requestType); FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No session factory manager"); diff --git a/sshd-core/src/main/java/org/apache/sshd/server/forward/TcpipServerChannel.java b/sshd-core/src/main/java/org/apache/sshd/server/forward/TcpipServerChannel.java index b621353..8782af5 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/forward/TcpipServerChannel.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/forward/TcpipServerChannel.java @@ -144,7 +144,8 @@ public class TcpipServerChannel extends AbstractServerChannel implements Forward int originatorPort = buffer.getInt(); boolean debugEnabled = log.isDebugEnabled(); if (debugEnabled) { - log.debug("doInit({}) Receiving request for direct tcpip: hostToConnect={}, portToConnect={}, originatorIpAddress={}, originatorPort={}", + log.debug("doInit({}) Receiving request for direct tcpip:" + + " hostToConnect={}, portToConnect={}, originatorIpAddress={}, originatorPort={}", this, hostToConnect, portToConnect, originatorIpAddress, originatorPort); } @@ -194,7 +195,8 @@ public class TcpipServerChannel extends AbstractServerChannel implements Forward } // TODO: revisit for better threading. Use async io ? - out = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + out = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); IoHandler handler = new IoHandler() { @Override @SuppressWarnings("synthetic-access") @@ -235,7 +237,9 @@ public class TcpipServerChannel extends AbstractServerChannel implements Forward IoServiceFactory ioServiceFactory = manager.getIoServiceFactory(); connector = ioServiceFactory.createConnector(handler); - IoConnectFuture future = connector.connect(address.toInetSocketAddress(), null, getLocalAddress()); + + IoConnectFuture future = + connector.connect(address.toInetSocketAddress(), null, getLocalAddress()); future.addListener(future1 -> handleChannelConnectResult(f, future1)); return f; } @@ -284,7 +288,8 @@ public class TcpipServerChannel extends AbstractServerChannel implements Forward notifyStateChanged(problem.getClass().getSimpleName()); try { if (problem instanceof ConnectException) { - f.setException(new SshChannelOpenException(getId(), SshConstants.SSH_OPEN_CONNECT_FAILED, problem.getMessage(), problem)); + f.setException(new SshChannelOpenException( + getId(), SshConstants.SSH_OPEN_CONNECT_FAILED, problem.getMessage(), problem)); } else { f.setException(problem); } @@ -343,16 +348,19 @@ public class TcpipServerChannel extends AbstractServerChannel implements Forward Buffer buf = ByteArrayBuffer.getCompactClone(data, off, (int) len); ioSession.writePacket(buf).addListener(future -> { if (future.isWritten()) { - handleWriteDataSuccess(SshConstants.SSH_MSG_CHANNEL_DATA, buf.array(), 0, (int) len); + handleWriteDataSuccess( + SshConstants.SSH_MSG_CHANNEL_DATA, buf.array(), 0, (int) len); } else { - handleWriteDataFailure(SshConstants.SSH_MSG_CHANNEL_DATA, buf.array(), 0, (int) len, future.getException()); + handleWriteDataFailure( + SshConstants.SSH_MSG_CHANNEL_DATA, buf.array(), 0, (int) len, future.getException()); } }); } @Override protected void doWriteExtendedData(byte[] data, int off, long len) throws IOException { - throw new UnsupportedOperationException(getTcpipChannelType() + "Tcpip channel does not support extended data"); + throw new UnsupportedOperationException( + getTcpipChannelType() + "Tcpip channel does not support extended data"); } protected void handleWriteDataSuccess(byte cmd, byte[] data, int off, int len) { @@ -379,8 +387,9 @@ public class TcpipServerChannel extends AbstractServerChannel implements Forward } if (log.isTraceEnabled()) { - log.trace("handleWriteDataFailure(" + this + ")[" + SshConstants.getCommandMessageName(cmd & 0xFF) + "]" - + " len=" + len + " write failure details", t); + log.trace("handleWriteDataFailure(" + this + ")" + + "[" + SshConstants.getCommandMessageName(cmd & 0xFF) + "]" + + " len=" + len + " write failure details", t); } if (ioSession.isOpen()) { diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java b/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java index 4043017..08d2d74 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java @@ -93,7 +93,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override public ServerProxyAcceptor getServerProxyAcceptor() { - return resolveEffectiveProvider(ServerProxyAcceptor.class, proxyAcceptor, getFactoryManager().getServerProxyAcceptor()); + return resolveEffectiveProvider( + ServerProxyAcceptor.class, proxyAcceptor, getFactoryManager().getServerProxyAcceptor()); } @Override @@ -113,7 +114,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override public PasswordAuthenticator getPasswordAuthenticator() { ServerFactoryManager manager = getFactoryManager(); - return resolveEffectiveProvider(PasswordAuthenticator.class, passwordAuthenticator, manager.getPasswordAuthenticator()); + return resolveEffectiveProvider( + PasswordAuthenticator.class, passwordAuthenticator, manager.getPasswordAuthenticator()); } @Override @@ -124,7 +126,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override public PublickeyAuthenticator getPublickeyAuthenticator() { ServerFactoryManager manager = getFactoryManager(); - return resolveEffectiveProvider(PublickeyAuthenticator.class, publickeyAuthenticator, manager.getPublickeyAuthenticator()); + return resolveEffectiveProvider( + PublickeyAuthenticator.class, publickeyAuthenticator, manager.getPublickeyAuthenticator()); } @Override @@ -135,7 +138,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override public KeyboardInteractiveAuthenticator getKeyboardInteractiveAuthenticator() { ServerFactoryManager manager = getFactoryManager(); - return resolveEffectiveProvider(KeyboardInteractiveAuthenticator.class, interactiveAuthenticator, manager.getKeyboardInteractiveAuthenticator()); + return resolveEffectiveProvider( + KeyboardInteractiveAuthenticator.class, interactiveAuthenticator, manager.getKeyboardInteractiveAuthenticator()); } @Override @@ -146,7 +150,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override public GSSAuthenticator getGSSAuthenticator() { ServerFactoryManager manager = getFactoryManager(); - return resolveEffectiveProvider(GSSAuthenticator.class, gssAuthenticator, manager.getGSSAuthenticator()); + return resolveEffectiveProvider( + GSSAuthenticator.class, gssAuthenticator, manager.getGSSAuthenticator()); } @Override @@ -157,7 +162,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override public HostBasedAuthenticator getHostBasedAuthenticator() { ServerFactoryManager manager = getFactoryManager(); - return resolveEffectiveProvider(HostBasedAuthenticator.class, hostBasedAuthenticator, manager.getHostBasedAuthenticator()); + return resolveEffectiveProvider( + HostBasedAuthenticator.class, hostBasedAuthenticator, manager.getHostBasedAuthenticator()); } @Override @@ -356,7 +362,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S /* * Make sure we can provide key(s) for the available signatures */ - ValidateUtils.checkTrue(proposedManager == getFactoryManager(), "Mismatched signatures proposed factory manager"); + ValidateUtils.checkTrue(proposedManager == getFactoryManager(), + "Mismatched signatures proposed factory manager"); KeyPairProvider kpp = getKeyPairProvider(); boolean debugEnabled = log.isDebugEnabled(); @@ -373,7 +380,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S throw new RuntimeSshException(e); } - Collection<String> available = NamedResource.getNameList(getSignatureFactories()); + Collection<String> available = + NamedResource.getNameList(getSignatureFactories()); if ((provided == null) || GenericUtils.isEmpty(available)) { return resolveEmptySignaturesProposal(available, provided); } @@ -411,7 +419,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S boolean debugEnabled = log.isDebugEnabled(); if (acceptor != null) { try { - boolean completed = acceptor.acceptServerProxyMetadata(this, buffer); + boolean completed = + acceptor.acceptServerProxyMetadata(this, buffer); if (!completed) { buffer.rpos(rpos); // restore original buffer position return false; // more data required @@ -483,7 +492,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S public KeyPair getHostKey() { String proposedKey = getNegotiatedKexParameter(KexProposalOption.SERVERKEYS); String keyType = KeyUtils.getCanonicalKeyType(proposedKey); - KeyPairProvider provider = Objects.requireNonNull(getKeyPairProvider(), "No host keys provider"); + KeyPairProvider provider = + Objects.requireNonNull(getKeyPairProvider(), "No host keys provider"); try { return provider.loadKey(this, keyType); } catch (IOException | GeneralSecurityException | Error e) { @@ -518,7 +528,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S } String sessionUser = session.getUsername(); - if ((!GenericUtils.isEmpty(sessionUser)) && Objects.equals(sessionUser, userName)) { + if ((!GenericUtils.isEmpty(sessionUser)) + && Objects.equals(sessionUser, userName)) { totalCount++; } } @@ -538,6 +549,8 @@ public abstract class AbstractServerSession extends AbstractSession implements S @Override protected ConnectionService getConnectionService() { - return (this.currentService instanceof ConnectionService) ? (ConnectionService) this.currentService : null; + return (this.currentService instanceof ConnectionService) + ? (ConnectionService) this.currentService + : null; } } diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerSessionImpl.java b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerSessionImpl.java index dbe3019..876f3a8 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerSessionImpl.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerSessionImpl.java @@ -33,7 +33,8 @@ public class ServerSessionImpl extends AbstractServerSession { signalSessionCreated(ioSession); String headerConfig = this.getString(ServerFactoryManager.SERVER_EXTRA_IDENTIFICATION_LINES); - String[] headers = GenericUtils.split(headerConfig, ServerFactoryManager.SERVER_EXTRA_IDENT_LINES_SEPARATOR); + String[] headers = GenericUtils.split( + headerConfig, ServerFactoryManager.SERVER_EXTRA_IDENT_LINES_SEPARATOR); sendServerIdentification(headers); } } diff --git a/sshd-core/src/main/java/org/apache/sshd/server/x11/ChannelForwardedX11.java b/sshd-core/src/main/java/org/apache/sshd/server/x11/ChannelForwardedX11.java index a7abc9f..48d7b90 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/x11/ChannelForwardedX11.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/x11/ChannelForwardedX11.java @@ -79,9 +79,12 @@ public class ChannelForwardedX11 extends AbstractClientChannel { @Override protected synchronized void doOpen() throws IOException { if (Streaming.Async.equals(streaming)) { - throw new IllegalArgumentException("Asynchronous streaming isn't supported yet on this channel"); + throw new IllegalArgumentException( + "Asynchronous streaming isn't supported yet on this channel"); } - out = new ChannelOutputStream(this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); + + out = new ChannelOutputStream( + this, getRemoteWindow(), log, SshConstants.SSH_MSG_CHANNEL_DATA, true); invertedIn = out; } @@ -92,11 +95,13 @@ public class ChannelForwardedX11 extends AbstractClientChannel { @Override protected synchronized void doWriteData(byte[] data, int off, long len) throws IOException { - ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, "Data length exceeds int boundaries: %d", len); + ValidateUtils.checkTrue(len <= Integer.MAX_VALUE, + "Data length exceeds int boundaries: %d", len); Window wLocal = getLocalWindow(); wLocal.consumeAndCheck(len); // use a clone in case data buffer is re-used - serverSession.writePacket(ByteArrayBuffer.getCompactClone(data, off, (int) len)); + Buffer packet = ByteArrayBuffer.getCompactClone(data, off, (int) len); + serverSession.writePacket(packet); } @Override diff --git a/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/AbstractSftpSubsystemHelper.java b/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/AbstractSftpSubsystemHelper.java index d489e5f..b171d1b 100644 --- a/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/AbstractSftpSubsystemHelper.java +++ b/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/AbstractSftpSubsystemHelper.java @@ -206,10 +206,14 @@ public abstract class AbstractSftpSubsystemHelper protected AbstractSftpSubsystemHelper( UnsupportedAttributePolicy policy, SftpFileSystemAccessor accessor, SftpErrorStatusDataHandler handler) { - unsupportedAttributePolicy = Objects.requireNonNull(policy, "No unsupported attribute policy provided"); - fileSystemAccessor = Objects.requireNonNull(accessor, "No file system accessor"); - sftpEventListenerProxy = EventListenerUtils.proxyWrapper(SftpEventListener.class, getClass().getClassLoader(), sftpEventListeners); - errorStatusDataHandler = Objects.requireNonNull(handler, "No error status data handler"); + unsupportedAttributePolicy = + Objects.requireNonNull(policy, "No unsupported attribute policy provided"); + fileSystemAccessor = + Objects.requireNonNull(accessor, "No file system accessor"); + sftpEventListenerProxy = + EventListenerUtils.proxyWrapper(SftpEventListener.class, getClass().getClassLoader(), sftpEventListeners); + errorStatusDataHandler = + Objects.requireNonNull(handler, "No error status data handler"); } @Override @@ -316,8 +320,10 @@ public abstract class AbstractSftpSubsystemHelper Integer sftpVersion = session.getInteger(SftpSubsystemEnvironment.SFTP_VERSION); if (sftpVersion != null) { int forcedValue = sftpVersion; - if ((forcedValue < SftpSubsystemEnvironment.LOWER_SFTP_IMPL) || (forcedValue > SftpSubsystemEnvironment.HIGHER_SFTP_IMPL)) { - throw new IllegalStateException("Forced SFTP version (" + sftpVersion + ") not within supported values: " + available); + if ((forcedValue < SftpSubsystemEnvironment.LOWER_SFTP_IMPL) + || (forcedValue > SftpSubsystemEnvironment.HIGHER_SFTP_IMPL)) { + throw new IllegalStateException( + "Forced SFTP version (" + sftpVersion + ") not within supported values: " + available); } hig = sftpVersion; low = hig; @@ -541,7 +547,9 @@ public abstract class AbstractSftpSubsystemHelper * @return The assigned (opaque) handle * @throws IOException if failed to execute */ - protected abstract String doOpen(int id, String path, int pflags, int access, Map<String, Object> attrs) throws IOException; + protected abstract String doOpen( + int id, String path, int pflags, int access, Map<String, Object> attrs) + throws IOException; protected <E extends IOException> E signalOpenFailure( int id, String pathValue, Path path, boolean isDir, E thrown) @@ -576,7 +584,8 @@ public abstract class AbstractSftpSubsystemHelper long offset = buffer.getLong(); int requestedLength = buffer.getInt(); ServerSession session = getServerSession(); - int maxAllowed = session.getIntProperty(MAX_READDATA_PACKET_LENGTH_PROP, DEFAULT_MAX_READDATA_PACKET_LENGTH); + int maxAllowed = session.getIntProperty( + MAX_READDATA_PACKET_LENGTH_PROP, DEFAULT_MAX_READDATA_PACKET_LENGTH); int readLen = Math.min(requestedLength, maxAllowed); if (log.isTraceEnabled()) { log.trace("doRead({})[id={}]({})[offset={}] - req={}, max={}, effective={}", @@ -609,7 +618,9 @@ public abstract class AbstractSftpSubsystemHelper send(buffer); } - protected abstract int doRead(int id, String handle, long offset, int length, byte[] data, int doff) throws IOException; + protected abstract int doRead( + int id, String handle, long offset, int length, byte[] data, int doff) + throws IOException; protected void doWrite(Buffer buffer, int id) throws IOException { String handle = buffer.getString(); @@ -626,8 +637,8 @@ public abstract class AbstractSftpSubsystemHelper } protected abstract void doWrite( - int id, String handle, long offset, int length, byte[] data, int doff, int remaining) - throws IOException; + int id, String handle, long offset, int length, byte[] data, int doff, int remaining) + throws IOException; protected void doLStat(Buffer buffer, int id) throws IOException { String path = buffer.getString(); @@ -750,7 +761,9 @@ public abstract class AbstractSftpSubsystemHelper sendHandle(prepareReply(buffer), id, handle); } - protected abstract String doOpenDir(int id, String path, Path p, LinkOption... options) throws IOException; + protected abstract String doOpenDir( + int id, String path, Path p, LinkOption... options) + throws IOException; protected abstract void doReadDir(Buffer buffer, int id) throws IOException; @@ -767,7 +780,8 @@ public abstract class AbstractSftpSubsystemHelper doLink(id, targetPath, linkPath, symLink); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_LINK, targetPath, linkPath, symLink); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_LINK, targetPath, linkPath, symLink); return; } @@ -788,7 +802,8 @@ public abstract class AbstractSftpSubsystemHelper } doSymLink(id, targetPath, linkPath); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_SYMLINK, targetPath, linkPath); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_SYMLINK, targetPath, linkPath); return; } @@ -799,7 +814,9 @@ public abstract class AbstractSftpSubsystemHelper createLink(id, targetPath, linkPath, true); } - protected abstract void createLink(int id, String existingPath, String linkPath, boolean symLink) throws IOException; + protected abstract void createLink( + int id, String existingPath, String linkPath, boolean symLink) + throws IOException; // see https://github.com/openssh/openssh-portable/blob/master/PROTOCOL section 10 protected void doOpenSSHHardLink(Buffer buffer, int id) throws IOException { @@ -832,7 +849,8 @@ public abstract class AbstractSftpSubsystemHelper try { info = doSpaceAvailable(id, path); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_EXTENDED, SftpConstants.EXT_SPACE_AVAILABLE, path); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_EXTENDED, SftpConstants.EXT_SPACE_AVAILABLE, path); return; } @@ -866,7 +884,8 @@ public abstract class AbstractSftpSubsystemHelper // TODO : implement text-seek - see https://tools.ietf.org/html/draft-ietf-secsh-filexfer-03#section-6.3 doTextSeek(id, handle, line); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_EXTENDED, SftpConstants.EXT_TEXT_SEEK, handle, line); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_EXTENDED, SftpConstants.EXT_TEXT_SEEK, handle, line); return; } @@ -881,7 +900,8 @@ public abstract class AbstractSftpSubsystemHelper try { doOpenSSHFsync(id, handle); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_EXTENDED, FsyncExtensionParser.NAME, handle); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_EXTENDED, FsyncExtensionParser.NAME, handle); return; } @@ -902,10 +922,12 @@ public abstract class AbstractSftpSubsystemHelper buffer.putByte((byte) SftpConstants.SSH_FXP_EXTENDED_REPLY); buffer.putInt(id); buffer.putString(SftpConstants.EXT_CHECK_FILE); - doCheckFileHash(id, targetType, target, Arrays.asList(algos), startOffset, length, blockSize, buffer); + doCheckFileHash(id, targetType, target, + Arrays.asList(algos), startOffset, length, blockSize, buffer); } catch (Exception e) { sendStatus(prepareReply(buffer), id, e, - SftpConstants.SSH_FXP_EXTENDED, targetType, target, algList, startOffset, length, blockSize); + SftpConstants.SSH_FXP_EXTENDED, targetType, target, + algList, startOffset, length, blockSize); return; } @@ -918,7 +940,9 @@ public abstract class AbstractSftpSubsystemHelper throws Exception { ValidateUtils.checkTrue(startOffset >= 0L, "Invalid start offset: %d", startOffset); ValidateUtils.checkTrue(length >= 0L, "Invalid length: %d", length); - ValidateUtils.checkTrue((blockSize == 0) || (blockSize >= SftpConstants.MIN_CHKFILE_BLOCKSIZE), "Invalid block size: %d", blockSize); + ValidateUtils.checkTrue( + (blockSize == 0) || (blockSize >= SftpConstants.MIN_CHKFILE_BLOCKSIZE), + "Invalid block size: %d", blockSize); Objects.requireNonNull(factory, "No digest factory provided"); buffer.putString(factory.getName()); @@ -932,7 +956,8 @@ public abstract class AbstractSftpSubsystemHelper effectiveLength = totalLength - startOffset; } } - ValidateUtils.checkTrue(effectiveLength > 0L, "Non-positive effective hash data length: %d", effectiveLength); + ValidateUtils.checkTrue(effectiveLength > 0L, + "Non-positive effective hash data length: %d", effectiveLength); byte[] digestBuf = (blockSize == 0) ? new byte[Math.min((int) effectiveLength, IoUtils.DEFAULT_COPY_SIZE)] @@ -1022,7 +1047,8 @@ public abstract class AbstractSftpSubsystemHelper } catch (Exception e) { sendStatus(prepareReply(buffer), id, e, - SftpConstants.SSH_FXP_EXTENDED, targetType, target, startOffset, length, quickCheckHash); + SftpConstants.SSH_FXP_EXTENDED, targetType, target, + startOffset, length, quickCheckHash); return; } @@ -1035,10 +1061,12 @@ public abstract class AbstractSftpSubsystemHelper } protected abstract byte[] doMD5Hash( - int id, String targetType, String target, long startOffset, long length, byte[] quickCheckHash) - throws Exception; + int id, String targetType, String target, long startOffset, long length, byte[] quickCheckHash) + throws Exception; - protected byte[] doMD5Hash(int id, Path path, long startOffset, long length, byte[] quickCheckHash) throws Exception { + protected byte[] doMD5Hash( + int id, Path path, long startOffset, long length, byte[] quickCheckHash) + throws Exception { ValidateUtils.checkTrue(startOffset >= 0L, "Invalid start offset: %d", startOffset); ValidateUtils.checkTrue(length > 0L, "Invalid length: %d", length); if (!BuiltinDigests.md5.isSupported()) { @@ -1185,7 +1213,8 @@ public abstract class AbstractSftpSubsystemHelper try { doRename(id, oldPath, newPath, flags); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_RENAME, oldPath, newPath, flags); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_RENAME, oldPath, newPath, flags); return; } @@ -1220,7 +1249,10 @@ public abstract class AbstractSftpSubsystemHelper listener.moving(session, o, n, opts); try { - Files.move(o, n, GenericUtils.isEmpty(opts) ? IoUtils.EMPTY_COPY_OPTIONS : opts.toArray(new CopyOption[opts.size()])); + Files.move(o, n, + GenericUtils.isEmpty(opts) + ? IoUtils.EMPTY_COPY_OPTIONS + : opts.toArray(new CopyOption[opts.size()])); } catch (IOException | RuntimeException e) { listener.moved(session, o, n, opts, e); throw e; @@ -1248,8 +1280,8 @@ public abstract class AbstractSftpSubsystemHelper } protected abstract void doCopyData( - int id, String readHandle, long readOffset, long readLength, String writeHandle, long writeOffset) - throws IOException; + int id, String readHandle, long readOffset, long readLength, String writeHandle, long writeOffset) + throws IOException; // see https://tools.ietf.org/html/draft-ietf-secsh-filexfer-extensions-00#section-6 protected void doCopyFile(Buffer buffer, int id) throws IOException { @@ -1268,7 +1300,9 @@ public abstract class AbstractSftpSubsystemHelper sendStatus(prepareReply(buffer), id, SftpConstants.SSH_FX_OK, ""); } - protected void doCopyFile(int id, String srcFile, String dstFile, boolean overwriteDestination) throws IOException { + protected void doCopyFile( + int id, String srcFile, String dstFile, boolean overwriteDestination) + throws IOException { if (log.isDebugEnabled()) { log.debug("doCopyFile({})[id={}] SSH_FXP_EXTENDED[{}] (src={}, dst={}, overwrite=0x{})", getServerSession(), id, SftpConstants.EXT_COPY_FILE, @@ -1281,10 +1315,15 @@ public abstract class AbstractSftpSubsystemHelper : Collections.emptyList()); } - protected void doCopyFile(int id, String srcFile, String dstFile, Collection<CopyOption> opts) throws IOException { + protected void doCopyFile( + int id, String srcFile, String dstFile, Collection<CopyOption> opts) + throws IOException { Path src = resolveFile(srcFile); Path dst = resolveFile(dstFile); - Files.copy(src, dst, GenericUtils.isEmpty(opts) ? IoUtils.EMPTY_COPY_OPTIONS : opts.toArray(new CopyOption[opts.size()])); + Files.copy(src, dst, + GenericUtils.isEmpty(opts) + ? IoUtils.EMPTY_COPY_OPTIONS + : opts.toArray(new CopyOption[opts.size()])); } protected void doBlock(Buffer buffer, int id) throws IOException { @@ -1303,7 +1342,9 @@ public abstract class AbstractSftpSubsystemHelper sendStatus(prepareReply(buffer), id, SftpConstants.SSH_FX_OK, ""); } - protected abstract void doBlock(int id, String handle, long offset, long length, int mask) throws IOException; + protected abstract void doBlock( + int id, String handle, long offset, long length, int mask) + throws IOException; protected void doUnblock(Buffer buffer, int id) throws IOException { String handle = buffer.getString(); @@ -1312,14 +1353,17 @@ public abstract class AbstractSftpSubsystemHelper try { doUnblock(id, handle, offset, length); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_UNBLOCK, handle, offset, length); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_UNBLOCK, handle, offset, length); return; } sendStatus(prepareReply(buffer), id, SftpConstants.SSH_FX_OK, ""); } - protected abstract void doUnblock(int id, String handle, long offset, long length) throws IOException; + protected abstract void doUnblock( + int id, String handle, long offset, long length) + throws IOException; protected void doStat(Buffer buffer, int id) throws IOException { String path = buffer.getString(); @@ -1333,7 +1377,8 @@ public abstract class AbstractSftpSubsystemHelper try { attrs = doStat(id, path, flags); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_STAT, path, flags); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_STAT, path, flags); return; } @@ -1415,7 +1460,8 @@ public abstract class AbstractSftpSubsystemHelper switch (control) { case SftpConstants.SSH_FXP_REALPATH_STAT_IF: if (status == null) { - attrs = handleUnknownStatusFileAttributes(p, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); + attrs = handleUnknownStatusFileAttributes( + p, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); } else if (status) { try { attrs = getAttributes(p, options); @@ -1436,11 +1482,13 @@ public abstract class AbstractSftpSubsystemHelper break; case SftpConstants.SSH_FXP_REALPATH_STAT_ALWAYS: if (status == null) { - attrs = handleUnknownStatusFileAttributes(p, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); + attrs = handleUnknownStatusFileAttributes( + p, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); } else if (status) { attrs = getAttributes(p, options); } else { - throw new NoSuchFileException(p.toString(), p.toString(), "Real path N/A for target"); + throw new NoSuchFileException( + p.toString(), p.toString(), "Real path N/A for target"); } break; case SftpConstants.SSH_FXP_REALPATH_NO_CHECK: @@ -1459,19 +1507,22 @@ public abstract class AbstractSftpSubsystemHelper } protected SimpleImmutableEntry<Path, Boolean> doRealPathV6( - int id, String path, Collection<String> extraPaths, Path p, LinkOption... options) throws IOException { + int id, String path, Collection<String> extraPaths, Path p, LinkOption... options) + throws IOException { int numExtra = GenericUtils.size(extraPaths); if (numExtra > 0) { if (log.isDebugEnabled()) { log.debug("doRealPathV6({})[id={}] path={}, extra={}", getServerSession(), id, path, extraPaths); } - StringBuilder sb = new StringBuilder(GenericUtils.length(path) + numExtra * 8); + StringBuilder sb = + new StringBuilder(GenericUtils.length(path) + numExtra * 8); sb.append(path); for (String p2 : extraPaths) { p = p.resolve(p2); - options = getPathResolutionLinkOption(SftpConstants.SSH_FXP_REALPATH, "", p); + options = getPathResolutionLinkOption( + SftpConstants.SSH_FXP_REALPATH, "", p); sb.append('/').append(p2); } @@ -1510,14 +1561,17 @@ public abstract class AbstractSftpSubsystemHelper try { doRemoveDirectory(id, path, IoUtils.getLinkOptions(false)); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_RMDIR, path); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_RMDIR, path); return; } sendStatus(prepareReply(buffer), id, SftpConstants.SSH_FX_OK, ""); } - protected void doRemoveDirectory(int id, String path, LinkOption... options) throws IOException { + protected void doRemoveDirectory( + int id, String path, LinkOption... options) + throws IOException { Path p = resolveFile(path); if (log.isDebugEnabled()) { log.debug("doRemoveDirectory({})[id={}] SSH_FXP_RMDIR (path={})[{}]", @@ -1526,7 +1580,8 @@ public abstract class AbstractSftpSubsystemHelper if (Files.isDirectory(p, options)) { doRemove(id, p, true); } else { - throw signalRemovalPreConditionFailure(id, path, p, new NotDirectoryException(p.toString()), true); + throw signalRemovalPreConditionFailure( + id, path, p, new NotDirectoryException(p.toString()), true); } } @@ -1558,14 +1613,17 @@ public abstract class AbstractSftpSubsystemHelper try { doMakeDirectory(id, path, attrs, IoUtils.getLinkOptions(false)); } catch (IOException | RuntimeException e) { - sendStatus(prepareReply(buffer), id, e, SftpConstants.SSH_FXP_MKDIR, path, attrs); + sendStatus(prepareReply(buffer), id, e, + SftpConstants.SSH_FXP_MKDIR, path, attrs); return; } sendStatus(prepareReply(buffer), id, SftpConstants.SSH_FX_OK, ""); } - protected void doMakeDirectory(int id, String path, Map<String, ?> attrs, LinkOption... options) throws IOException { + protected void doMakeDirectory( + int id, String path, Map<String, ?> attrs, LinkOption... options) + throws IOException { Path p = resolveFile(path); ServerSession session = getServerSession(); if (log.isDebugEnabled()) { @@ -1575,14 +1633,17 @@ public abstract class AbstractSftpSubsystemHelper Boolean status = IoUtils.checkFileExists(p, options); if (status == null) { - throw new AccessDeniedException(p.toString(), p.toString(), "Cannot validate make-directory existence"); + throw new AccessDeniedException( + p.toString(), p.toString(), "Cannot validate make-directory existence"); } if (status) { if (Files.isDirectory(p, options)) { - throw new FileAlreadyExistsException(p.toString(), p.toString(), "Target directory already exists"); + throw new FileAlreadyExistsException( + p.toString(), p.toString(), "Target directory already exists"); } else { - throw new FileAlreadyExistsException(p.toString(), p.toString(), "Already exists as a file"); + throw new FileAlreadyExistsException( + p.toString(), p.toString(), "Already exists as a file"); } } else { SftpEventListener listener = getSftpEventListenerProxy(); @@ -1626,13 +1687,16 @@ public abstract class AbstractSftpSubsystemHelper Boolean status = IoUtils.checkFileExists(p, options); if (status == null) { throw signalRemovalPreConditionFailure(id, path, p, - new AccessDeniedException(p.toString(), p.toString(), "Cannot determine existence of remove candidate"), false); + new AccessDeniedException( + p.toString(), p.toString(), "Cannot determine existence of remove candidate"), false); } else if (!status) { throw signalRemovalPreConditionFailure(id, path, p, - new NoSuchFileException(p.toString(), p.toString(), "Removal candidate not found"), false); + new NoSuchFileException( + p.toString(), p.toString(), "Removal candidate not found"), false); } else if (Files.isDirectory(p, options)) { throw signalRemovalPreConditionFailure(id, path, p, - new SftpException(SftpConstants.SSH_FX_FILE_IS_A_DIRECTORY, p.toString() + " is a folder"), false); + new SftpException( + SftpConstants.SSH_FX_FILE_IS_A_DIRECTORY, p.toString() + " is a folder"), false); } else { doRemove(id, p, false); } @@ -1702,9 +1766,12 @@ public abstract class AbstractSftpSubsystemHelper } } - protected void doUnsupportedExtension(Buffer buffer, int id, String extension) throws IOException { + protected void doUnsupportedExtension( + Buffer buffer, int id, String extension) + throws IOException { if (log.isDebugEnabled()) { - log.debug("executeExtendedCommand({}) received unsupported SSH_FXP_EXTENDED({})", getServerSession(), extension); + log.debug("executeExtendedCommand({}) received unsupported SSH_FXP_EXTENDED({})", + getServerSession(), extension); } sendStatus(prepareReply(buffer), id, SftpConstants.SSH_FX_OP_UNSUPPORTED, "Command SSH_FXP_EXTENDED(" + extension + ") is unsupported or not implemented"); @@ -1827,11 +1894,14 @@ public abstract class AbstractSftpSubsystemHelper } int pos = nvp.indexOf('='); - ValidateUtils.checkTrue((pos > 0) && (pos < (nvp.length() - 1)), "Malformed OpenSSH extension spec: %s", nvp); + ValidateUtils.checkTrue( + (pos > 0) && (pos < (nvp.length() - 1)), "Malformed OpenSSH extension spec: %s", nvp); + String name = GenericUtils.trimToEmpty(nvp.substring(0, pos)); String version = GenericUtils.trimToEmpty(nvp.substring(pos + 1)); extList.add(new OpenSSHExtension(name, - ValidateUtils.checkNotNullAndNotEmpty(version, "No version specified for OpenSSH extension %s", name))); + ValidateUtils.checkNotNullAndNotEmpty( + version, "No version specified for OpenSSH extension %s", name))); } return extList; @@ -1874,7 +1944,8 @@ public abstract class AbstractSftpSubsystemHelper * @param session The {@link ServerSession} for which this extension is added * @see SftpConstants#EXT_VERSIONS */ - protected void appendVersionsExtension(Buffer buffer, String value, ServerSession session) { + protected void appendVersionsExtension( + Buffer buffer, String value, ServerSession session) { if (GenericUtils.isEmpty(value)) { return; } @@ -1938,7 +2009,8 @@ public abstract class AbstractSftpSubsystemHelper * @see SftpConstants#EXT_VENDOR_ID * @see <A HREF="http://tools.ietf.org/wg/secsh/draft-ietf-secsh-filexfer/draft-ietf-secsh-filexfer-09.txt">DRAFT 09 - section 4.4</A> */ - protected void appendVendorIdExtension(Buffer buffer, Map<String, ?> versionProperties, ServerSession session) { + protected void appendVendorIdExtension( + Buffer buffer, Map<String, ?> versionProperties, ServerSession session) { if (GenericUtils.isEmpty(versionProperties)) { return; } @@ -1949,7 +2021,8 @@ public abstract class AbstractSftpSubsystemHelper buffer.putString(SftpConstants.EXT_VENDOR_ID); PropertyResolver resolver = - PropertyResolverUtils.toPropertyResolver(Collections.unmodifiableMap(versionProperties)); + PropertyResolverUtils.toPropertyResolver( + Collections.unmodifiableMap(versionProperties)); // placeholder for length int lenPos = buffer.wpos(); buffer.putInt(0); @@ -2076,7 +2149,9 @@ public abstract class AbstractSftpSubsystemHelper send(buffer); } - protected void sendPath(Buffer buffer, int id, Path f, Map<String, ?> attrs) throws IOException { + protected void sendPath( + Buffer buffer, int id, Path f, Map<String, ?> attrs) + throws IOException { buffer.putByte((byte) SftpConstants.SSH_FXP_NAME); buffer.putInt(id); buffer.putInt(1); // one reply @@ -2145,9 +2220,11 @@ public abstract class AbstractSftpSubsystemHelper * @throws IOException If failed to generate the entry data */ protected void writeDirEntry( - int id, DirectoryHandle dir, Map<String, Path> entries, Buffer buffer, int index, Path f, String shortName, LinkOption... options) + int id, DirectoryHandle dir, Map<String, Path> entries, Buffer buffer, + int index, Path f, String shortName, LinkOption... options) throws IOException { - Map<String, ?> attrs = resolveFileAttributes(f, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); + Map<String, ?> attrs = resolveFileAttributes( + f, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); entries.put(shortName, f); buffer.putString(shortName); @@ -2169,11 +2246,15 @@ public abstract class AbstractSftpSubsystemHelper writeAttrs(buffer, attrs); } - protected String getLongName(Path f, String shortName, LinkOption... options) throws IOException { + protected String getLongName( + Path f, String shortName, LinkOption... options) + throws IOException { return getLongName(f, shortName, true, options); } - protected String getLongName(Path f, String shortName, boolean sendAttrs, LinkOption... options) throws IOException { + protected String getLongName( + Path f, String shortName, boolean sendAttrs, LinkOption... options) + throws IOException { Map<String, Object> attributes; if (sendAttrs) { attributes = getAttributes(f, options); @@ -2183,7 +2264,9 @@ public abstract class AbstractSftpSubsystemHelper return getLongName(f, shortName, attributes); } - protected String getLongName(Path f, String shortName, Map<String, ?> attributes) throws IOException { + protected String getLongName( + Path f, String shortName, Map<String, ?> attributes) + throws IOException { return SftpHelper.getLongName(shortName, attributes); } @@ -2224,7 +2307,9 @@ public abstract class AbstractSftpSubsystemHelper } } - protected NavigableMap<String, Object> resolveFileAttributes(Path file, int flags, LinkOption... options) throws IOException { + protected NavigableMap<String, Object> resolveFileAttributes( + Path file, int flags, LinkOption... options) + throws IOException { Boolean status = IoUtils.checkFileExists(file, options); if (status == null) { return handleUnknownStatusFileAttributes(file, flags, options); @@ -2239,17 +2324,21 @@ public abstract class AbstractSftpSubsystemHelper SftpHelper.writeAttrs(buffer, getVersion(), attributes); } - protected NavigableMap<String, Object> getAttributes(Path file, LinkOption... options) throws IOException { + protected NavigableMap<String, Object> getAttributes(Path file, LinkOption... options) + throws IOException { return getAttributes(file, SftpConstants.SSH_FILEXFER_ATTR_ALL, options); } - protected NavigableMap<String, Object> handleUnknownStatusFileAttributes(Path file, int flags, LinkOption... options) throws IOException { + protected NavigableMap<String, Object> handleUnknownStatusFileAttributes( + Path file, int flags, LinkOption... options) + throws IOException { UnsupportedAttributePolicy unsupportedAttributePolicy = getUnsupportedAttributePolicy(); switch (unsupportedAttributePolicy) { case Ignore: break; case ThrowException: - throw new AccessDeniedException(file.toString(), file.toString(), "Cannot determine existence for attributes of target"); + throw new AccessDeniedException( + file.toString(), file.toString(), "Cannot determine existence for attributes of target"); case Warn: log.warn("handleUnknownStatusFileAttributes(" + getServerSession() + ")[" + file + "] cannot determine existence"); break; @@ -2270,7 +2359,8 @@ public abstract class AbstractSftpSubsystemHelper * @throws IOException If failed to access the file * @see #resolveMissingFileAttributes(Path, int, Map, LinkOption...) */ - protected NavigableMap<String, Object> getAttributes(Path file, int flags, LinkOption... options) throws IOException { + protected NavigableMap<String, Object> getAttributes(Path file, int flags, LinkOption... options) + throws IOException { FileSystem fs = file.getFileSystem(); Collection<String> supportedViews = fs.supportedFileAttributeViews(); NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); @@ -2291,7 +2381,8 @@ public abstract class AbstractSftpSubsystemHelper } } - Map<String, ?> completions = resolveMissingFileAttributes(file, flags, attrs, options); + Map<String, ?> completions = + resolveMissingFileAttributes(file, flags, attrs, options); if (GenericUtils.isNotEmpty(completions)) { attrs.putAll(completions); } @@ -2320,7 +2411,8 @@ public abstract class AbstractSftpSubsystemHelper * @see SftpFileSystemAccessor#FILEATTRS_RESOLVERS */ protected NavigableMap<String, Object> resolveMissingFileAttributes( - Path file, int flags, Map<String, Object> current, LinkOption... options) throws IOException { + Path file, int flags, Map<String, Object> current, LinkOption... options) + throws IOException { boolean debugEnabled = log.isDebugEnabled(); NavigableMap<String, Object> attrs = null; // Cannot use forEach because the attrs variable is not effectively final @@ -2363,7 +2455,9 @@ public abstract class AbstractSftpSubsystemHelper } } - protected Object resolveMissingFileAttributeValue(Path file, String name, Object value, FileInfoExtractor<?> x, LinkOption... options) throws IOException { + protected Object resolveMissingFileAttributeValue( + Path file, String name, Object value, FileInfoExtractor<?> x, LinkOption... options) + throws IOException { if (value != null) { return value; } else { @@ -2372,7 +2466,9 @@ public abstract class AbstractSftpSubsystemHelper } protected NavigableMap<String, Object> addMissingAttribute( - Path file, NavigableMap<String, Object> current, String name, FileInfoExtractor<?> x, LinkOption... options) throws IOException { + Path file, NavigableMap<String, Object> current, + String name, FileInfoExtractor<?> x, LinkOption... options) + throws IOException { Object value = GenericUtils.isEmpty(current) ? null : current.get(name); if (value != null) { // already have the value return current; @@ -2392,14 +2488,17 @@ public abstract class AbstractSftpSubsystemHelper return current; } - protected NavigableMap<String, Object> readFileAttributes(Path file, String view, LinkOption... options) throws IOException { + protected NavigableMap<String, Object> readFileAttributes( + Path file, String view, LinkOption... options) + throws IOException { try { Map<String, ?> attrs = Files.readAttributes(file, view, options); if (GenericUtils.isEmpty(attrs)) { return Collections.emptyNavigableMap(); } - NavigableMap<String, Object> sorted = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + NavigableMap<String, Object> sorted = + new TreeMap<>(String.CASE_INSENSITIVE_ORDER); sorted.putAll(attrs); return sorted; } catch (IOException e) { @@ -2407,7 +2506,9 @@ public abstract class AbstractSftpSubsystemHelper } } - protected NavigableMap<String, Object> handleReadFileAttributesException(Path file, String view, LinkOption[] options, IOException e) throws IOException { + protected NavigableMap<String, Object> handleReadFileAttributesException( + Path file, String view, LinkOption[] options, IOException e) + throws IOException { if (log.isTraceEnabled()) { log.trace("handleReadFileAttributesException(" + file + ")[" + view + "] details", e); } @@ -2430,7 +2531,9 @@ public abstract class AbstractSftpSubsystemHelper return Collections.emptyNavigableMap(); } - protected void doSetAttributes(Path file, Map<String, ?> attributes, boolean followLinks) throws IOException { + protected void doSetAttributes( + Path file, Map<String, ?> attributes, boolean followLinks) + throws IOException { SftpEventListener listener = getSftpEventListenerProxy(); ServerSession session = getServerSession(); listener.modifyingAttributes(session, file, attributes); @@ -2443,18 +2546,22 @@ public abstract class AbstractSftpSubsystemHelper listener.modifiedAttributes(session, file, attributes, null); } - protected LinkOption[] getPathResolutionLinkOption(int cmd, String extension, Path path) throws IOException { + protected LinkOption[] getPathResolutionLinkOption(int cmd, String extension, Path path) + throws IOException { boolean followLinks = resolvePathResolutionFollowLinks(cmd, extension, path); return IoUtils.getLinkOptions(followLinks); } - protected boolean resolvePathResolutionFollowLinks(int cmd, String extension, Path path) throws IOException { + protected boolean resolvePathResolutionFollowLinks(int cmd, String extension, Path path) + throws IOException { ServerSession session = getServerSession(); return PropertyResolverUtils.getBooleanProperty( session, AUTO_FOLLOW_LINKS, DEFAULT_AUTO_FOLLOW_LINKS); } - protected void setFileAttributes(Path file, Map<String, ?> attributes, LinkOption... options) throws IOException { + protected void setFileAttributes( + Path file, Map<String, ?> attributes, LinkOption... options) + throws IOException { Set<String> unsupported = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); // Cannot use forEach because of the potential IOException being thrown for (Map.Entry<String, ?> ae : attributes.entrySet()) { @@ -2521,7 +2628,8 @@ public abstract class AbstractSftpSubsystemHelper } protected void handleSetFileAttributeFailure( - Path file, String view, String attribute, Object value, Collection<String> unsupported, Exception e) + Path file, String view, String attribute, Object value, + Collection<String> unsupported, Exception e) throws IOException { boolean debugEnabled = log.isDebugEnabled(); if (e instanceof UnsupportedOperationException) { @@ -2546,9 +2654,12 @@ public abstract class AbstractSftpSubsystemHelper } } - protected void setFileAttribute(Path file, String view, String attribute, Object value, LinkOption... options) throws IOException { + protected void setFileAttribute( + Path file, String view, String attribute, Object value, LinkOption... options) + throws IOException { if (log.isTraceEnabled()) { - log.trace("setFileAttribute({})[{}] {}:{}={}", getServerSession(), file, view, attribute, value); + log.trace("setFileAttribute({})[{}] {}:{}={}", + getServerSession(), file, view, attribute, value); } if ("acl".equalsIgnoreCase(attribute) && "acl".equalsIgnoreCase(view)) { @@ -2574,19 +2685,24 @@ public abstract class AbstractSftpSubsystemHelper } } - protected void setFileTime(Path file, String view, String attribute, FileTime value, LinkOption... options) throws IOException { + protected void setFileTime( + Path file, String view, String attribute, FileTime value, LinkOption... options) + throws IOException { if (value == null) { return; } if (log.isDebugEnabled()) { - log.debug("setFileTime({})[{}] {}:{}={}", getServerSession(), file, view, attribute, value); + log.debug("setFileTime({})[{}] {}:{}={}", + getServerSession(), file, view, attribute, value); } Files.setAttribute(file, view + ":" + attribute, value, options); } - protected void setFileOwnership(Path file, String attribute, Principal value, LinkOption... options) throws IOException { + protected void setFileOwnership( + Path file, String attribute, Principal value, LinkOption... options) + throws IOException { if (value == null) { return; } @@ -2603,24 +2719,28 @@ public abstract class AbstractSftpSubsystemHelper * to set the file owner to a user principal that is not a group. */ if ("owner".equalsIgnoreCase(attribute)) { - FileOwnerAttributeView view = Files.getFileAttributeView(file, FileOwnerAttributeView.class, options); + FileOwnerAttributeView view = + Files.getFileAttributeView(file, FileOwnerAttributeView.class, options); if (view == null) { throw new UnsupportedOperationException("Owner view not supported for " + file); } if (!(value instanceof UserPrincipal)) { - throw new StreamCorruptedException("Owner is not " + UserPrincipal.class.getSimpleName() + ": " + value.getClass().getSimpleName()); + throw new StreamCorruptedException( + "Owner is not " + UserPrincipal.class.getSimpleName() + ": " + value.getClass().getSimpleName()); } view.setOwner((UserPrincipal) value); } else if ("group".equalsIgnoreCase(attribute)) { - PosixFileAttributeView view = Files.getFileAttributeView(file, PosixFileAttributeView.class, options); + PosixFileAttributeView view = + Files.getFileAttributeView(file, PosixFileAttributeView.class, options); if (view == null) { throw new UnsupportedOperationException("POSIX view not supported"); } if (!(value instanceof GroupPrincipal)) { - throw new StreamCorruptedException("Group is not " + GroupPrincipal.class.getSimpleName() + ": " + value.getClass().getSimpleName()); + throw new StreamCorruptedException( + "Group is not " + GroupPrincipal.class.getSimpleName() + ": " + value.getClass().getSimpleName()); } view.setGroup((GroupPrincipal) value); @@ -2629,7 +2749,9 @@ public abstract class AbstractSftpSubsystemHelper } } - protected void setFileExtensions(Path file, Map<String, byte[]> extensions, LinkOption... options) throws IOException { + protected void setFileExtensions( + Path file, Map<String, byte[]> extensions, LinkOption... options) + throws IOException { if (GenericUtils.isEmpty(extensions)) { return; } @@ -2651,13 +2773,16 @@ public abstract class AbstractSftpSubsystemHelper } } - protected void setFilePermissions(Path file, Set<PosixFilePermission> perms, LinkOption... options) throws IOException { + protected void setFilePermissions( + Path file, Set<PosixFilePermission> perms, LinkOption... options) + throws IOException { if (OsUtils.isWin32()) { IoUtils.setPermissionsToFile(file.toFile(), perms); return; } - PosixFileAttributeView view = Files.getFileAttributeView(file, PosixFileAttributeView.class, options); + PosixFileAttributeView view = + Files.getFileAttributeView(file, PosixFileAttributeView.class, options); if (view == null) { throw new UnsupportedOperationException("POSIX view not supported for " + file); } @@ -2668,8 +2793,11 @@ public abstract class AbstractSftpSubsystemHelper view.setPermissions(perms); } - protected void setFileAccessControl(Path file, List<AclEntry> acl, LinkOption... options) throws IOException { - AclFileAttributeView view = Files.getFileAttributeView(file, AclFileAttributeView.class, options); + protected void setFileAccessControl( + Path file, List<AclEntry> acl, LinkOption... options) + throws IOException { + AclFileAttributeView view = + Files.getFileAttributeView(file, AclFileAttributeView.class, options); if (view == null) { throw new UnsupportedOperationException("ACL view not supported for " + file); } @@ -2703,7 +2831,8 @@ public abstract class AbstractSftpSubsystemHelper protected GroupPrincipal toGroup(Path file, GroupPrincipal name) throws IOException { String groupName = name.toString(); FileSystem fileSystem = file.getFileSystem(); - UserPrincipalLookupService lookupService = fileSystem.getUserPrincipalLookupService(); + UserPrincipalLookupService lookupService = + fileSystem.getUserPrincipalLookupService(); try { if (lookupService == null) { throw new UserPrincipalNotFoundException(groupName); @@ -2718,7 +2847,8 @@ public abstract class AbstractSftpSubsystemHelper protected UserPrincipal toUser(Path file, UserPrincipal name) throws IOException { String username = name.toString(); FileSystem fileSystem = file.getFileSystem(); - UserPrincipalLookupService lookupService = fileSystem.getUserPrincipalLookupService(); + UserPrincipalLookupService lookupService = + fileSystem.getUserPrincipalLookupService(); try { if (lookupService == null) { throw new UserPrincipalNotFoundException(username); @@ -2731,7 +2861,9 @@ public abstract class AbstractSftpSubsystemHelper } } - protected void handleUserPrincipalLookupServiceException(Class<? extends Principal> principalType, String name, IOException e) throws IOException { + protected void handleUserPrincipalLookupServiceException( + Class<? extends Principal> principalType, String name, IOException e) + throws IOException { if (log.isTraceEnabled()) { log.trace("handleUserPrincipalLookupServiceException(" + principalType.getSimpleName() + "[" + name + "]) details", e); } @@ -2796,7 +2928,8 @@ public abstract class AbstractSftpSubsystemHelper * <U>logging</U> purposes and subject to type and/or order change at any version * @throws IOException If failed to build and send the status buffer */ - protected void sendStatus(Buffer buffer, int id, Throwable e, int cmd, Object... args) throws IOException { + protected void sendStatus(Buffer buffer, int id, Throwable e, int cmd, Object... args) + throws IOException { SftpErrorStatusDataHandler handler = getErrorStatusDataHandler(); int subStatus = handler.resolveSubStatus(this, id, e, cmd, args); String message = handler.resolveErrorMessage(this, id, e, subStatus, cmd, args); @@ -2808,7 +2941,9 @@ public abstract class AbstractSftpSubsystemHelper sendStatus(buffer, id, substatus, (msg != null) ? msg : "", ""); } - protected void sendStatus(Buffer buffer, int id, int substatus, String msg, String lang) throws IOException { + protected void sendStatus( + Buffer buffer, int id, int substatus, String msg, String lang) + throws IOException { if (log.isDebugEnabled()) { log.debug("doSendStatus({})[id={}] SSH_FXP_STATUS (substatus={}, lang={}, msg={})", getServerSession(), id, SftpConstants.getStatusName(substatus), lang, msg); @@ -2826,7 +2961,8 @@ public abstract class AbstractSftpSubsystemHelper protected abstract void send(Buffer buffer) throws IOException; - protected Path resolveNormalizedLocation(String remotePath) throws IOException, InvalidPathException { + protected Path resolveNormalizedLocation(String remotePath) + throws IOException, InvalidPathException { Path resolvedPath = resolveFile(remotePath); return normalize(resolvedPath); } @@ -2846,9 +2982,11 @@ public abstract class AbstractSftpSubsystemHelper * @throws IOException If failed to resolve the local path * @throws InvalidPathException If bad local path specification */ - protected Path resolveFile(String remotePath) throws IOException, InvalidPathException { + protected Path resolveFile(String remotePath) + throws IOException, InvalidPathException { Path defaultDir = getDefaultDirectory(); - String path = SelectorUtils.translateToLocalFileSystemPath(remotePath, '/', defaultDir.getFileSystem()); + String path = SelectorUtils.translateToLocalFileSystemPath( + remotePath, '/', defaultDir.getFileSystem()); Path p = defaultDir.resolve(path); if (log.isTraceEnabled()) { log.trace("resolveFile({}) {} => {}", getServerSession(), remotePath, p); diff --git a/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java b/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java index 29f0c9f..c9bfd97 100644 --- a/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java +++ b/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java @@ -197,12 +197,16 @@ public class SftpSubsystem this.randomizer = factory.create(); this.fileHandleSize = session.getIntProperty(FILE_HANDLE_SIZE, DEFAULT_FILE_HANDLE_SIZE); - ValidateUtils.checkTrue(this.fileHandleSize >= MIN_FILE_HANDLE_SIZE, "File handle size too small: %d", this.fileHandleSize); - ValidateUtils.checkTrue(this.fileHandleSize <= MAX_FILE_HANDLE_SIZE, "File handle size too big: %d", this.fileHandleSize); + ValidateUtils.checkTrue(this.fileHandleSize >= MIN_FILE_HANDLE_SIZE, + "File handle size too small: %d", this.fileHandleSize); + ValidateUtils.checkTrue(this.fileHandleSize <= MAX_FILE_HANDLE_SIZE, + "File handle size too big: %d", this.fileHandleSize); this.maxFileHandleRounds = session.getIntProperty(MAX_FILE_HANDLE_RAND_ROUNDS, DEFAULT_FILE_HANDLE_ROUNDS); - ValidateUtils.checkTrue(this.maxFileHandleRounds >= MIN_FILE_HANDLE_ROUNDS, "File handle rounds too small: %d", this.maxFileHandleRounds); - ValidateUtils.checkTrue(this.maxFileHandleRounds <= MAX_FILE_HANDLE_ROUNDS, "File handle rounds too big: %d", this.maxFileHandleRounds); + ValidateUtils.checkTrue(this.maxFileHandleRounds >= MIN_FILE_HANDLE_ROUNDS, + "File handle rounds too small: %d", this.maxFileHandleRounds); + ValidateUtils.checkTrue(this.maxFileHandleRounds <= MAX_FILE_HANDLE_ROUNDS, + "File handle rounds too big: %d", this.maxFileHandleRounds); if (workBuf.length < this.fileHandleSize) { workBuf = new byte[this.fileHandleSize]; @@ -344,7 +348,9 @@ public class SftpSubsystem } @Override - protected void createLink(int id, String existingPath, String linkPath, boolean symLink) throws IOException { + protected void createLink( + int id, String existingPath, String linkPath, boolean symLink) + throws IOException { Path link = resolveFile(linkPath); Path existing = fileSystem.getPath(existingPath); ServerSession session = getServerSession(); @@ -391,7 +397,8 @@ public class SftpSubsystem FileHandle fileHandle = validateHandle(handle, h, FileHandle.class); SftpFileSystemAccessor accessor = getFileSystemAccessor(); accessor.syncFileData( - session, this, fileHandle, fileHandle.getFile(), fileHandle.getFileHandle(), fileHandle.getFileChannel()); + session, this, fileHandle, fileHandle.getFile(), + fileHandle.getFileHandle(), fileHandle.getFileChannel()); } @Override @@ -413,7 +420,8 @@ public class SftpSubsystem */ int access = fileHandle.getAccessMask(); if ((access & SftpConstants.ACE4_READ_DATA) == 0) { - throw new AccessDeniedException(path.toString(), path.toString(), "File not opened for read"); + throw new AccessDeniedException( + path.toString(), path.toString(), "File not opened for read"); } } else { path = resolveFile(target); @@ -580,12 +588,15 @@ public class SftpSubsystem @Override @SuppressWarnings("resource") - protected void doCopyData(int id, String readHandle, long readOffset, long readLength, String writeHandle, long writeOffset) throws IOException { + protected void doCopyData( + int id, String readHandle, long readOffset, long readLength, String writeHandle, long writeOffset) + throws IOException { boolean inPlaceCopy = readHandle.equals(writeHandle); Handle rh = handles.get(readHandle); Handle wh = inPlaceCopy ? rh : handles.get(writeHandle); if (log.isDebugEnabled()) { - log.debug("doCopyData({})[id={}] SSH_FXP_EXTENDED[{}] read={}[{}], read-offset={}, read-length={}, write={}[{}], write-offset={})", + log.debug("doCopyData({})[id={}] SSH_FXP_EXTENDED[{}] read={}[{}]" + + ", read-offset={}, read-length={}, write={}[{}], write-offset={})", getServerSession(), id, SftpConstants.EXT_COPY_DATA, readHandle, rh, readOffset, readLength, writeHandle, wh, writeOffset); @@ -595,7 +606,8 @@ public class SftpSubsystem Path srcPath = srcHandle.getFile(); int srcAccess = srcHandle.getAccessMask(); if ((srcAccess & SftpConstants.ACE4_READ_DATA) != SftpConstants.ACE4_READ_DATA) { - throw new AccessDeniedException(srcPath.toString(), srcPath.toString(), "Source file not opened for read"); + throw new AccessDeniedException( + srcPath.toString(), srcPath.toString(), "Source file not opened for read"); } ValidateUtils.checkTrue(readLength >= 0L, "Invalid read length: %d", readLength); @@ -611,12 +623,15 @@ public class SftpSubsystem effectiveLength = totalSize - readOffset; } } - ValidateUtils.checkTrue(effectiveLength > 0L, "Non-positive effective copy data length: %d", effectiveLength); + ValidateUtils.checkTrue(effectiveLength > 0L, + "Non-positive effective copy data length: %d", effectiveLength); - FileHandle dstHandle = inPlaceCopy ? srcHandle : validateHandle(writeHandle, wh, FileHandle.class); + FileHandle dstHandle = + inPlaceCopy ? srcHandle : validateHandle(writeHandle, wh, FileHandle.class); int dstAccess = dstHandle.getAccessMask(); if ((dstAccess & SftpConstants.ACE4_WRITE_DATA) != SftpConstants.ACE4_WRITE_DATA) { - throw new AccessDeniedException(srcHandle.toString(), srcHandle.toString(), "Source handle not opened for write"); + throw new AccessDeniedException( + srcHandle.toString(), srcHandle.toString(), "Source handle not opened for write"); } ValidateUtils.checkTrue(writeOffset >= 0L, "Invalid write offset: %d", writeOffset); @@ -675,7 +690,8 @@ public class SftpSubsystem getPathResolutionLinkOption(SftpConstants.SSH_FXP_READDIR, "", file); Boolean status = IoUtils.checkFileExists(file, options); if (status == null) { - throw new AccessDeniedException(file.toString(), file.toString(), "Cannot determine existence of read-dir"); + throw new AccessDeniedException( + file.toString(), file.toString(), "Cannot determine existence of read-dir"); } if (!status) { @@ -786,7 +802,9 @@ public class SftpSubsystem } @Override - protected void doWrite(int id, String handle, long offset, int length, byte[] data, int doff, int remaining) throws IOException { + protected void doWrite( + int id, String handle, long offset, int length, byte[] data, int doff, int remaining) + throws IOException { Handle h = handles.get(handle); ServerSession session = getServerSession(); if (log.isTraceEnabled()) { @@ -820,7 +838,9 @@ public class SftpSubsystem } @Override - protected int doRead(int id, String handle, long offset, int length, byte[] data, int doff) throws IOException { + protected int doRead( + int id, String handle, long offset, int length, byte[] data, int doff) + throws IOException { Handle h = handles.get(handle); ServerSession session = getServerSession(); if (log.isTraceEnabled()) { @@ -865,7 +885,9 @@ public class SftpSubsystem } @Override - protected String doOpen(int id, String path, int pflags, int access, Map<String, Object> attrs) throws IOException { + protected String doOpen( + int id, String path, int pflags, int access, Map<String, Object> attrs) + throws IOException { ServerSession session = getServerSession(); if (log.isDebugEnabled()) { log.debug("doOpen({})[id={}] SSH_FXP_OPEN (path={}, access=0x{}, pflags=0x{}, attrs={})", @@ -874,7 +896,8 @@ public class SftpSubsystem Path file = resolveFile(path); int curHandleCount = handles.size(); - int maxHandleCount = session.getIntProperty(MAX_OPEN_HANDLES_PER_SESSION, DEFAULT_MAX_OPEN_HANDLES); + int maxHandleCount = session.getIntProperty( + MAX_OPEN_HANDLES_PER_SESSION, DEFAULT_MAX_OPEN_HANDLES); if (curHandleCount > maxHandleCount) { throw signalOpenFailure(id, path, file, false, new SftpException(SftpConstants.SSH_FX_NO_SPACE_ON_FILESYSTEM, @@ -903,11 +926,13 @@ public class SftpSubsystem boolean traceEnabled = log.isTraceEnabled(); for (int index = 0; index < maxFileHandleRounds; index++) { randomizer.fill(workBuf, 0, fileHandleSize); - String handle = BufferUtils.toHex(workBuf, 0, fileHandleSize, BufferUtils.EMPTY_HEX_SEPARATOR); + String handle = BufferUtils.toHex( + workBuf, 0, fileHandleSize, BufferUtils.EMPTY_HEX_SEPARATOR); if (handles.containsKey(handle)) { if (traceEnabled) { - log.trace("generateFileHandle({})[{}] handle={} in use at round {}", session, file, handle, index); + log.trace("generateFileHandle({})[{}] handle={} in use at round {}", + session, file, handle, index); } continue; } @@ -929,7 +954,8 @@ public class SftpSubsystem } Map.Entry<Integer, String> negotiated = - checkVersionCompatibility(buffer, id, id, SftpConstants.SSH_FX_OP_UNSUPPORTED); + checkVersionCompatibility( + buffer, id, id, SftpConstants.SSH_FX_OP_UNSUPPORTED); if (negotiated == null) { // i.e. validation failed return; }