Changes for injecting a LoggingFactory.

This commit is contained in:
David Solin
2016-08-23 19:13:43 -05:00
parent 8c1329036a
commit 219901211e
45 changed files with 374 additions and 218 deletions

View File

@@ -17,20 +17,21 @@ package com.hierynomus.sshj.transport;
import net.schmizz.sshj.common.Buffer; import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.ByteArrayUtils; import net.schmizz.sshj.common.ByteArrayUtils;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.transport.TransportException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
public class IdentificationStringParser { public class IdentificationStringParser {
private static final Logger logger = LoggerFactory.getLogger(IdentificationStringParser.class); private final Logger log;
private final Buffer.PlainBuffer buffer; private final Buffer.PlainBuffer buffer;
private byte[] EXPECTED_START_BYTES = new byte[] {'S', 'S', 'H', '-'}; private byte[] EXPECTED_START_BYTES = new byte[] {'S', 'S', 'H', '-'};
public IdentificationStringParser(Buffer.PlainBuffer buffer) { public IdentificationStringParser(LoggerFactory loggerFactory, Buffer.PlainBuffer buffer) {
this.log = loggerFactory.getLogger(IdentificationStringParser.class);
this.buffer = buffer; this.buffer = buffer;
} }
@@ -65,16 +66,16 @@ public class IdentificationStringParser {
byte[] bytes = new byte[lineBuffer.available()]; byte[] bytes = new byte[lineBuffer.available()];
lineBuffer.readRawBytes(bytes); lineBuffer.readRawBytes(bytes);
if (bytes.length > 255) { if (bytes.length > 255) {
logger.error("Incorrect identification String received, line was longer than expected: {}", new String(bytes)); log.error("Incorrect identification String received, line was longer than expected: {}", new String(bytes));
logger.error("Just for good measure, bytes were: {}", ByteArrayUtils.printHex(bytes, 0, bytes.length)); log.error("Just for good measure, bytes were: {}", ByteArrayUtils.printHex(bytes, 0, bytes.length));
throw new TransportException("Incorrect identification: line too long: " + ByteArrayUtils.printHex(bytes, 0, bytes.length)); throw new TransportException("Incorrect identification: line too long: " + ByteArrayUtils.printHex(bytes, 0, bytes.length));
} }
if (bytes[bytes.length - 2] != '\r') { if (bytes[bytes.length - 2] != '\r') {
String ident = new String(bytes, 0, bytes.length - 1); String ident = new String(bytes, 0, bytes.length - 1);
logger.warn("Server identification has bad line ending, was expecting a '\\r\\n' however got: '{}' (hex: {})", (char) (bytes[bytes.length - 2] & 0xFF), Integer.toHexString(bytes[bytes.length - 2] & 0xFF)); log.warn("Server identification has bad line ending, was expecting a '\\r\\n' however got: '{}' (hex: {})", (char) (bytes[bytes.length - 2] & 0xFF), Integer.toHexString(bytes[bytes.length - 2] & 0xFF));
logger.warn("Will treat the identification of this server '{}' leniently", ident); log.warn("Will treat the identification of this server '{}' leniently", ident);
return ident; return ident;
// logger.error("Data received up til here was: {}", new String(bytes)); // log.error("Data received up til here was: {}", new String(bytes));
// throw new TransportException("Incorrect identification: bad line ending: " + ByteArrayUtils.toHex(bytes, 0, bytes.length)); // throw new TransportException("Incorrect identification: bad line ending: " + ByteArrayUtils.toHex(bytes, 0, bytes.length));
} }

View File

@@ -18,6 +18,8 @@ package net.schmizz.concurrent;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import net.schmizz.sshj.common.LoggerFactory;
/** /**
* An event can be set, cleared, or awaited, similar to Python's {@code threading.event}. The key difference is that a * An event can be set, cleared, or awaited, similar to Python's {@code threading.event}. The key difference is that a
* waiter may be delivered an exception of parameterized type {@code T}. * waiter may be delivered an exception of parameterized type {@code T}.
@@ -42,8 +44,8 @@ public class Event<T extends Throwable> {
* @param name name of this event * @param name name of this event
* @param chainer {@link ExceptionChainer} that will be used for chaining exceptions * @param chainer {@link ExceptionChainer} that will be used for chaining exceptions
*/ */
public Event(String name, ExceptionChainer<T> chainer) { public Event(String name, ExceptionChainer<T> chainer, LoggerFactory loggerFactory) {
promise = new Promise<Object, T>(name, chainer); promise = new Promise<Object, T>(name, chainer, loggerFactory);
} }
/** /**
@@ -53,8 +55,8 @@ public class Event<T extends Throwable> {
* @param chainer {@link ExceptionChainer} that will be used for chaining exceptions * @param chainer {@link ExceptionChainer} that will be used for chaining exceptions
* @param lock lock to use * @param lock lock to use
*/ */
public Event(String name, ExceptionChainer<T> chainer, ReentrantLock lock) { public Event(String name, ExceptionChainer<T> chainer, ReentrantLock lock, LoggerFactory loggerFactory) {
promise = new Promise<Object, T>(name, chainer, lock); promise = new Promise<Object, T>(name, chainer, lock, loggerFactory);
} }
/** Sets this event to be {@code true}. Short for {@code set(true)}. */ /** Sets this event to be {@code true}. Short for {@code set(true)}. */

View File

@@ -16,13 +16,14 @@
package net.schmizz.concurrent; package net.schmizz.concurrent;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import net.schmizz.sshj.common.LoggerFactory;
/** /**
* Represents promised data of the parameterized type {@code V} and allows waiting on it. An exception may also be * Represents promised data of the parameterized type {@code V} and allows waiting on it. An exception may also be
* delivered to a waiter, and will be of the parameterized type {@code T}. * delivered to a waiter, and will be of the parameterized type {@code T}.
@@ -32,8 +33,7 @@ import java.util.concurrent.locks.ReentrantLock;
*/ */
public class Promise<V, T extends Throwable> { public class Promise<V, T extends Throwable> {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
private final String name; private final String name;
private final ExceptionChainer<T> chainer; private final ExceptionChainer<T> chainer;
private final ReentrantLock lock; private final ReentrantLock lock;
@@ -49,8 +49,8 @@ public class Promise<V, T extends Throwable> {
* @param name name of this promise * @param name name of this promise
* @param chainer {@link ExceptionChainer} that will be used for chaining exceptions * @param chainer {@link ExceptionChainer} that will be used for chaining exceptions
*/ */
public Promise(String name, ExceptionChainer<T> chainer) { public Promise(String name, ExceptionChainer<T> chainer, LoggerFactory loggerFactory) {
this(name, chainer, null); this(name, chainer, null, loggerFactory);
} }
/** /**
@@ -60,10 +60,11 @@ public class Promise<V, T extends Throwable> {
* @param chainer {@link ExceptionChainer} that will be used for chaining exceptions * @param chainer {@link ExceptionChainer} that will be used for chaining exceptions
* @param lock lock to use * @param lock lock to use
*/ */
public Promise(String name, ExceptionChainer<T> chainer, ReentrantLock lock) { public Promise(String name, ExceptionChainer<T> chainer, ReentrantLock lock, LoggerFactory loggerFactory) {
this.name = name; this.name = name;
this.chainer = chainer; this.chainer = chainer;
this.lock = lock == null ? new ReentrantLock() : lock; this.lock = lock == null ? new ReentrantLock() : lock;
this.log = loggerFactory.getLogger(getClass());
this.cond = this.lock.newCondition(); this.cond = this.lock.newCondition();
} }

View File

@@ -22,14 +22,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public abstract class KeepAlive extends Thread { public abstract class KeepAlive extends Thread {
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final Logger log;
protected final ConnectionImpl conn; protected final ConnectionImpl conn;
protected int keepAliveInterval = 0; protected int keepAliveInterval = 0;
protected KeepAlive(ConnectionImpl conn, String name) { protected KeepAlive(ConnectionImpl conn, String name) {
this.conn = conn; this.conn = conn;
log = conn.getTransport().getConfig().getLoggerFactory().getLogger(getClass());
setName(name); setName(name);
} }

View File

@@ -16,20 +16,20 @@
package net.schmizz.sshj; package net.schmizz.sshj;
import net.schmizz.sshj.common.DisconnectReason; import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.Message; import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHException; import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.Transport; import net.schmizz.sshj.transport.Transport;
import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.transport.TransportException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** An abstract class for {@link Service} that implements common or default functionality. */ /** An abstract class for {@link Service} that implements common or default functionality. */
public abstract class AbstractService public abstract class AbstractService
implements Service { implements Service {
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final Logger log;
/** Assigned name of this service */ /** Assigned name of this service */
protected final String name; protected final String name;
@@ -39,6 +39,7 @@ public abstract class AbstractService
public AbstractService(String name, Transport trans) { public AbstractService(String name, Transport trans) {
this.name = name; this.name = name;
this.trans = trans; this.trans = trans;
log = trans.getConfig().getLoggerFactory().getLogger(getClass());
} }
@Override @Override

View File

@@ -17,6 +17,7 @@ package net.schmizz.sshj;
import net.schmizz.keepalive.KeepAliveProvider; import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.common.Factory; import net.schmizz.sshj.common.Factory;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.signature.Signature; import net.schmizz.sshj.signature.Signature;
import net.schmizz.sshj.transport.cipher.Cipher; import net.schmizz.sshj.transport.cipher.Cipher;
import net.schmizz.sshj.transport.compression.Compression; import net.schmizz.sshj.transport.compression.Compression;
@@ -175,4 +176,14 @@ public interface Config {
* @param waitForServerIdentBeforeSendingClientIdent Whether to wait for the server ident. * @param waitForServerIdentBeforeSendingClientIdent Whether to wait for the server ident.
*/ */
void setWaitForServerIdentBeforeSendingClientIdent(boolean waitForServerIdentBeforeSendingClientIdent); void setWaitForServerIdentBeforeSendingClientIdent(boolean waitForServerIdentBeforeSendingClientIdent);
/**
* Sets the LoggerFactory to use.
*/
void setLoggerFactory(LoggerFactory loggerFactory);
/**
* @return The LoggerFactory the SSHClient will use.
*/
LoggerFactory getLoggerFactory();
} }

View File

@@ -16,6 +16,7 @@
package net.schmizz.sshj; package net.schmizz.sshj;
import net.schmizz.keepalive.KeepAliveProvider; import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.Factory; import net.schmizz.sshj.common.Factory;
import net.schmizz.sshj.signature.Signature; import net.schmizz.sshj.signature.Signature;
import net.schmizz.sshj.transport.cipher.Cipher; import net.schmizz.sshj.transport.cipher.Cipher;
@@ -45,6 +46,7 @@ public class ConfigImpl
private List<Factory.Named<FileKeyProvider>> fileKeyProviderFactories; private List<Factory.Named<FileKeyProvider>> fileKeyProviderFactories;
private boolean waitForServerIdentBeforeSendingClientIdent = false; private boolean waitForServerIdentBeforeSendingClientIdent = false;
private LoggerFactory loggerFactory;
@Override @Override
public List<Factory.Named<Cipher>> getCipherFactories() { public List<Factory.Named<Cipher>> getCipherFactories() {
@@ -169,4 +171,14 @@ public class ConfigImpl
public void setWaitForServerIdentBeforeSendingClientIdent(boolean waitForServerIdentBeforeSendingClientIdent) { public void setWaitForServerIdentBeforeSendingClientIdent(boolean waitForServerIdentBeforeSendingClientIdent) {
this.waitForServerIdentBeforeSendingClientIdent = waitForServerIdentBeforeSendingClientIdent; this.waitForServerIdentBeforeSendingClientIdent = waitForServerIdentBeforeSendingClientIdent;
} }
@Override
public LoggerFactory getLoggerFactory() {
return loggerFactory;
}
@Override
public void setLoggerFactory(LoggerFactory loggerFactory) {
this.loggerFactory = loggerFactory;
}
} }

View File

@@ -20,6 +20,7 @@ import com.hierynomus.sshj.transport.cipher.BlockCiphers;
import com.hierynomus.sshj.transport.cipher.StreamCiphers; import com.hierynomus.sshj.transport.cipher.StreamCiphers;
import net.schmizz.keepalive.KeepAliveProvider; import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.common.Factory; import net.schmizz.sshj.common.Factory;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SecurityUtils; import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.signature.SignatureDSA; import net.schmizz.sshj.signature.SignatureDSA;
import net.schmizz.sshj.signature.SignatureECDSA; import net.schmizz.sshj.signature.SignatureECDSA;
@@ -35,7 +36,6 @@ import net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile;
import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile; import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile;
import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile; import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
@@ -67,11 +67,12 @@ import java.util.List;
public class DefaultConfig public class DefaultConfig
extends ConfigImpl { extends ConfigImpl {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String VERSION = "SSHJ_0_17_2"; private static final String VERSION = "SSHJ_0_17_2";
private Logger log;
public DefaultConfig() { public DefaultConfig() {
setLoggerFactory(LoggerFactory.DEFAULT);
setVersion(VERSION); setVersion(VERSION);
final boolean bouncyCastleRegistered = SecurityUtils.isBouncyCastleRegistered(); final boolean bouncyCastleRegistered = SecurityUtils.isBouncyCastleRegistered();
initKeyExchangeFactories(bouncyCastleRegistered); initKeyExchangeFactories(bouncyCastleRegistered);
@@ -84,6 +85,30 @@ public class DefaultConfig
setKeepAliveProvider(KeepAliveProvider.HEARTBEAT); setKeepAliveProvider(KeepAliveProvider.HEARTBEAT);
} }
/**
* Default SLF4J-based implementation of the SSHJ LoggerFactory.
*/
public static class DefaultLoggerFactory implements LoggerFactory {
private DefaultLoggerFactory() {
}
@Override
public Logger getLogger(String name) {
return org.slf4j.LoggerFactory.getLogger(name);
}
@Override
public Logger getLogger(Class<?> clazz) {
return org.slf4j.LoggerFactory.getLogger(clazz);
}
}
@Override
public void setLoggerFactory(LoggerFactory loggerFactory) {
super.setLoggerFactory(loggerFactory);
log = loggerFactory.getLogger(getClass());
}
protected void initKeyExchangeFactories(boolean bouncyCastleRegistered) { protected void initKeyExchangeFactories(boolean bouncyCastleRegistered) {
if (bouncyCastleRegistered) if (bouncyCastleRegistered)
setKeyExchangeFactories(new Curve25519SHA256.Factory(), setKeyExchangeFactories(new Curve25519SHA256.Factory(),
@@ -141,7 +166,8 @@ public class DefaultConfig
BlockCiphers.TwofishCBC(), BlockCiphers.TwofishCBC(),
StreamCiphers.Arcfour(), StreamCiphers.Arcfour(),
StreamCiphers.Arcfour128(), StreamCiphers.Arcfour128(),
StreamCiphers.Arcfour256())); StreamCiphers.Arcfour256())
);
boolean warn = false; boolean warn = false;
// Ref. https://issues.apache.org/jira/browse/SSHD-24 // Ref. https://issues.apache.org/jira/browse/SSHD-24
@@ -167,17 +193,26 @@ public class DefaultConfig
} }
protected void initSignatureFactories() { protected void initSignatureFactories() {
setSignatureFactories(new SignatureECDSA.Factory(), new SignatureRSA.Factory(), new SignatureDSA.Factory(), new SignatureEdDSA.Factory()); setSignatureFactories(
new SignatureECDSA.Factory(),
new SignatureRSA.Factory(),
new SignatureDSA.Factory(),
new SignatureEdDSA.Factory()
);
} }
protected void initMACFactories() { protected void initMACFactories() {
setMACFactories(new HMACSHA1.Factory(), new HMACSHA196.Factory(), new HMACMD5.Factory(), setMACFactories(
new HMACMD596.Factory(), new HMACSHA2256.Factory(), new HMACSHA2512.Factory()); new HMACSHA1.Factory(),
new HMACSHA196.Factory(),
new HMACMD5.Factory(),
new HMACMD596.Factory(),
new HMACSHA2256.Factory(),
new HMACSHA2512.Factory()
);
} }
protected void initCompressionFactories() { protected void initCompressionFactories() {
setCompressionFactories(new NoneCompression.Factory()); setCompressionFactories(new NoneCompression.Factory());
} }
} }

View File

@@ -16,6 +16,7 @@
package net.schmizz.sshj; package net.schmizz.sshj;
import net.schmizz.sshj.common.Factory; import net.schmizz.sshj.common.Factory;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHException; import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.common.SecurityUtils; import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.connection.Connection; import net.schmizz.sshj.connection.Connection;
@@ -54,7 +55,6 @@ import net.schmizz.sshj.userauth.password.Resource;
import net.schmizz.sshj.xfer.scp.SCPFileTransfer; import net.schmizz.sshj.xfer.scp.SCPFileTransfer;
import org.ietf.jgss.Oid; import org.ietf.jgss.Oid;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginContext;
import java.io.Closeable; import java.io.Closeable;
@@ -114,7 +114,8 @@ public class SSHClient
public static final int DEFAULT_PORT = 22; public static final int DEFAULT_PORT = 22;
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final LoggerFactory loggerFactory;
protected final Logger log;
/** Transport layer */ /** Transport layer */
protected final Transport trans; protected final Transport trans;
@@ -139,6 +140,8 @@ public class SSHClient
*/ */
public SSHClient(Config config) { public SSHClient(Config config) {
super(DEFAULT_PORT); super(DEFAULT_PORT);
loggerFactory = config.getLoggerFactory();
log = loggerFactory.getLogger(getClass());
this.trans = new TransportImpl(config, this); this.trans = new TransportImpl(config, this);
this.auth = new UserAuthImpl(trans); this.auth = new UserAuthImpl(trans);
this.conn = new ConnectionImpl(trans, config.getKeepAliveProvider()); this.conn = new ConnectionImpl(trans, config.getKeepAliveProvider());
@@ -211,6 +214,7 @@ public class SSHClient
checkConnected(); checkConnected();
final Deque<UserAuthException> savedEx = new LinkedList<>(); final Deque<UserAuthException> savedEx = new LinkedList<>();
for (AuthMethod method: methods) { for (AuthMethod method: methods) {
method.setLoggerFactory(loggerFactory);
try { try {
if (auth.authenticate(username, (Service) conn, method, trans.getTimeoutMs())) if (auth.authenticate(username, (Service) conn, method, trans.getTimeoutMs()))
return; return;
@@ -626,7 +630,7 @@ public class SSHClient
*/ */
public void loadKnownHosts(File location) public void loadKnownHosts(File location)
throws IOException { throws IOException {
addHostKeyVerifier(new OpenSSHKnownHosts(location)); addHostKeyVerifier(new OpenSSHKnownHosts(location, loggerFactory));
} }
/** /**
@@ -644,7 +648,7 @@ public class SSHClient
*/ */
public LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters, public LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters,
ServerSocket serverSocket) { ServerSocket serverSocket) {
LocalPortForwarder forwarder = new LocalPortForwarder(conn, parameters, serverSocket); LocalPortForwarder forwarder = new LocalPortForwarder(conn, parameters, serverSocket, loggerFactory);
forwarders.add(forwarder); forwarders.add(forwarder);
return forwarder; return forwarder;
} }
@@ -673,7 +677,7 @@ public class SSHClient
public SCPFileTransfer newSCPFileTransfer() { public SCPFileTransfer newSCPFileTransfer() {
checkConnected(); checkConnected();
checkAuthenticated(); checkAuthenticated();
return new SCPFileTransfer(this); return new SCPFileTransfer(this, loggerFactory);
} }
/** /**

View File

@@ -16,7 +16,6 @@
package net.schmizz.sshj.common; package net.schmizz.sshj.common;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.Closeable; import java.io.Closeable;
@@ -26,24 +25,32 @@ import java.nio.charset.Charset;
public class IOUtils { public class IOUtils {
private static final Logger LOG = LoggerFactory.getLogger(IOUtils.class);
public static final Charset UTF8 = Charset.forName("UTF-8"); public static final Charset UTF8 = Charset.forName("UTF-8");
public static void closeQuietly(Closeable... closeables) { public static void closeQuietly(Closeable... closeables) {
for (Closeable c : closeables) closeQuietly(LoggerFactory.DEFAULT, closeables);
try {
if (c != null)
c.close();
} catch (IOException logged) {
LOG.warn("Error closing {} - {}", c, logged);
}
} }
public static ByteArrayOutputStream readFully(InputStream stream) public static ByteArrayOutputStream readFully(InputStream stream)
throws IOException { throws IOException {
return readFully(stream, LoggerFactory.DEFAULT);
}
public static void closeQuietly(LoggerFactory loggerFactory, Closeable... closeables) {
for (Closeable c : closeables) {
try {
if (c != null)
c.close();
} catch (IOException logged) {
loggerFactory.getLogger(IOUtils.class).warn("Error closing {} - {}", c, logged);
}
}
}
public static ByteArrayOutputStream readFully(InputStream stream, LoggerFactory loggerFactory)
throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
new StreamCopier(stream, baos).copy(); new StreamCopier(stream, baos, loggerFactory).copy();
return baos; return baos;
} }

View File

@@ -174,15 +174,15 @@ public enum KeyType {
}, },
ED25519("ssh-ed25519") { ED25519("ssh-ed25519") {
private final Logger logger = LoggerFactory.getLogger(KeyType.class); private final Logger log = LoggerFactory.getLogger(KeyType.class);
@Override @Override
public PublicKey readPubKeyFromBuffer(String type, Buffer<?> buf) throws GeneralSecurityException { public PublicKey readPubKeyFromBuffer(String type, Buffer<?> buf) throws GeneralSecurityException {
try { try {
final int keyLen = buf.readUInt32AsInt(); final int keyLen = buf.readUInt32AsInt();
final byte[] p = new byte[keyLen]; final byte[] p = new byte[keyLen];
buf.readRawBytes(p); buf.readRawBytes(p);
if (logger.isDebugEnabled()) { if (log.isDebugEnabled()) {
logger.debug(String.format("Key algo: %s, Key curve: 25519, Key Len: %s\np: %s", log.debug(String.format("Key algo: %s, Key curve: 25519, Key Len: %s\np: %s",
type, type,
keyLen, keyLen,
Arrays.toString(p)) Arrays.toString(p))

View File

@@ -15,10 +15,10 @@
*/ */
package net.schmizz.sshj.common; package net.schmizz.sshj.common;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.concurrent.Event; import net.schmizz.concurrent.Event;
import net.schmizz.concurrent.ExceptionChainer; import net.schmizz.concurrent.ExceptionChainer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -39,8 +39,8 @@ public class StreamCopier {
} }
}; };
private final Logger log = LoggerFactory.getLogger(getClass()); private final LoggerFactory loggerFactory;
private final Logger log;
private final InputStream in; private final InputStream in;
private final OutputStream out; private final OutputStream out;
@@ -50,9 +50,11 @@ public class StreamCopier {
private boolean keepFlushing = true; private boolean keepFlushing = true;
private long length = -1; private long length = -1;
public StreamCopier(InputStream in, OutputStream out) { public StreamCopier(InputStream in, OutputStream out, LoggerFactory loggerFactory) {
this.in = in; this.in = in;
this.out = out; this.out = out;
this.loggerFactory = loggerFactory;
this.log = loggerFactory.getLogger(getClass());
} }
public StreamCopier bufSize(int bufSize) { public StreamCopier bufSize(int bufSize) {
@@ -91,7 +93,7 @@ public class StreamCopier {
public IOException chain(Throwable t) { public IOException chain(Throwable t) {
return (t instanceof IOException) ? (IOException) t : new IOException(t); return (t instanceof IOException) ? (IOException) t : new IOException(t);
} }
}); }, loggerFactory);
new Thread() { new Thread() {
{ {

View File

@@ -17,6 +17,7 @@ package net.schmizz.sshj.connection;
import net.schmizz.concurrent.Promise; import net.schmizz.concurrent.Promise;
import net.schmizz.keepalive.KeepAlive; import net.schmizz.keepalive.KeepAlive;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.connection.channel.Channel; import net.schmizz.sshj.connection.channel.Channel;
import net.schmizz.sshj.connection.channel.OpenFailException; import net.schmizz.sshj.connection.channel.OpenFailException;

View File

@@ -199,7 +199,7 @@ public class ConnectionImpl
Promise<SSHPacket, ConnectionException> promise = null; Promise<SSHPacket, ConnectionException> promise = null;
if (wantReply) { if (wantReply) {
promise = new Promise<SSHPacket, ConnectionException>("global req for " + name, ConnectionException.chainer); promise = new Promise<SSHPacket, ConnectionException>("global req for " + name, ConnectionException.chainer, trans.getConfig().getLoggerFactory());
globalReqPromises.add(promise); globalReqPromises.add(promise);
} }
return promise; return promise;

View File

@@ -23,7 +23,6 @@ import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.transport.Transport; import net.schmizz.sshj.transport.Transport;
import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.transport.TransportException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@@ -38,7 +37,8 @@ public abstract class AbstractChannel
private static final int REMOTE_MAX_PACKET_SIZE_CEILING = 1024 * 1024; private static final int REMOTE_MAX_PACKET_SIZE_CEILING = 1024 * 1024;
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final LoggerFactory loggerFactory;
protected final Logger log;
/** Transport layer */ /** Transport layer */
protected final Transport trans; protected final Transport trans;
@@ -77,21 +77,23 @@ public abstract class AbstractChannel
protected AbstractChannel(Connection conn, String type) { protected AbstractChannel(Connection conn, String type) {
this.conn = conn; this.conn = conn;
this.loggerFactory = conn.getTransport().getConfig().getLoggerFactory();
this.type = type; this.type = type;
this.log = loggerFactory.getLogger(getClass());
this.trans = conn.getTransport(); this.trans = conn.getTransport();
id = conn.nextID(); id = conn.nextID();
lwin = new Window.Local(conn.getWindowSize(), conn.getMaxPacketSize()); lwin = new Window.Local(conn.getWindowSize(), conn.getMaxPacketSize(), loggerFactory);
in = new ChannelInputStream(this, trans, lwin); in = new ChannelInputStream(this, trans, lwin);
openEvent = new Event<ConnectionException>("chan#" + id + " / " + "open", ConnectionException.chainer, openCloseLock); openEvent = new Event<ConnectionException>("chan#" + id + " / " + "open", ConnectionException.chainer, openCloseLock, loggerFactory);
closeEvent = new Event<ConnectionException>("chan#" + id + " / " + "close", ConnectionException.chainer, openCloseLock); closeEvent = new Event<ConnectionException>("chan#" + id + " / " + "close", ConnectionException.chainer, openCloseLock, loggerFactory);
} }
protected void init(int recipient, long remoteWinSize, long remoteMaxPacketSize) { protected void init(int recipient, long remoteWinSize, long remoteMaxPacketSize) {
this.recipient = recipient; this.recipient = recipient;
rwin = new Window.Remote(remoteWinSize, (int) Math.min(remoteMaxPacketSize, REMOTE_MAX_PACKET_SIZE_CEILING)); rwin = new Window.Remote(remoteWinSize, (int) Math.min(remoteMaxPacketSize, REMOTE_MAX_PACKET_SIZE_CEILING), loggerFactory);
out = new ChannelOutputStream(this, trans, rwin); out = new ChannelOutputStream(this, trans, rwin);
log.debug("Initialized - {}", this); log.debug("Initialized - {}", this);
} }
@@ -189,6 +191,11 @@ public abstract class AbstractChannel
} }
} }
@Override
public LoggerFactory getLoggerFactory() {
return loggerFactory;
}
private void gotClose() private void gotClose()
throws TransportException { throws TransportException {
log.debug("Got close"); log.debug("Got close");
@@ -356,7 +363,7 @@ public abstract class AbstractChannel
Event<ConnectionException> responseEvent = null; Event<ConnectionException> responseEvent = null;
if (wantReply) { if (wantReply) {
responseEvent = new Event<ConnectionException>("chan#" + id + " / " + "chanreq for " + reqType, responseEvent = new Event<ConnectionException>("chan#" + id + " / " + "chanreq for " + reqType,
ConnectionException.chainer); ConnectionException.chainer, loggerFactory);
chanReqResponseEvents.add(responseEvent); chanReqResponseEvents.add(responseEvent);
} }
return responseEvent; return responseEvent;

View File

@@ -16,6 +16,7 @@
package net.schmizz.sshj.connection.channel; package net.schmizz.sshj.connection.channel;
import net.schmizz.sshj.common.ErrorNotifiable; import net.schmizz.sshj.common.ErrorNotifiable;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacketHandler; import net.schmizz.sshj.common.SSHPacketHandler;
import net.schmizz.sshj.connection.ConnectionException; import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.transport.TransportException;
@@ -134,4 +135,8 @@ public interface Channel
void join(long timeout, TimeUnit unit) void join(long timeout, TimeUnit unit)
throws ConnectionException; throws ConnectionException;
/**
* Get the LoggerFactory associated with the SSH client.
*/
LoggerFactory getLoggerFactory();
} }

View File

@@ -34,7 +34,7 @@ public final class ChannelInputStream
extends InputStream extends InputStream
implements ErrorNotifiable { implements ErrorNotifiable {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
private final Channel chan; private final Channel chan;
private final Transport trans; private final Transport trans;
@@ -47,6 +47,7 @@ public final class ChannelInputStream
public ChannelInputStream(Channel chan, Transport trans, Window.Local win) { public ChannelInputStream(Channel chan, Transport trans, Window.Local win) {
this.chan = chan; this.chan = chan;
log = chan.getLoggerFactory().getLogger(getClass());
this.trans = trans; this.trans = trans;
this.win = win; this.win = win;
buf = new Buffer.PlainBuffer(chan.getLocalMaxPacketSize()); buf = new Buffer.PlainBuffer(chan.getLocalMaxPacketSize());

View File

@@ -15,14 +15,14 @@
*/ */
package net.schmizz.sshj.connection.channel; package net.schmizz.sshj.connection.channel;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHRuntimeException; import net.schmizz.sshj.common.SSHRuntimeException;
import net.schmizz.sshj.connection.ConnectionException; import net.schmizz.sshj.connection.ConnectionException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Window { public abstract class Window {
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final Logger log;
protected final Object lock = new Object(); protected final Object lock = new Object();
@@ -30,9 +30,10 @@ public abstract class Window {
protected long size; protected long size;
public Window(long initialWinSize, int maxPacketSize) { public Window(long initialWinSize, int maxPacketSize, LoggerFactory loggerFactory) {
size = initialWinSize; size = initialWinSize;
this.maxPacketSize = maxPacketSize; this.maxPacketSize = maxPacketSize;
log = loggerFactory.getLogger(getClass());
} }
public void expand(long inc) { public void expand(long inc) {
@@ -72,8 +73,8 @@ public abstract class Window {
public static final class Remote public static final class Remote
extends Window { extends Window {
public Remote(long initialWinSize, int maxPacketSize) { public Remote(long initialWinSize, int maxPacketSize, LoggerFactory loggerFactory) {
super(initialWinSize, maxPacketSize); super(initialWinSize, maxPacketSize, loggerFactory);
} }
public long awaitExpansion(long was) public long awaitExpansion(long was)
@@ -108,8 +109,8 @@ public abstract class Window {
private final long initialSize; private final long initialSize;
private final long threshold; private final long threshold;
public Local(long initialWinSize, int maxPacketSize) { public Local(long initialWinSize, int maxPacketSize, LoggerFactory loggerFactory) {
super(initialWinSize, maxPacketSize); super(initialWinSize, maxPacketSize, loggerFactory);
this.initialSize = initialWinSize; this.initialSize = initialWinSize;
threshold = Math.min(maxPacketSize * 20, initialSize / 4); threshold = Math.min(maxPacketSize * 20, initialSize / 4);
} }

View File

@@ -16,6 +16,7 @@
package net.schmizz.sshj.connection.channel.direct; package net.schmizz.sshj.connection.channel.direct;
import net.schmizz.sshj.common.Buffer; import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.Message; import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.connection.Connection; import net.schmizz.sshj.connection.Connection;

View File

@@ -17,12 +17,12 @@ package net.schmizz.sshj.connection.channel.direct;
import net.schmizz.concurrent.Event; import net.schmizz.concurrent.Event;
import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.common.StreamCopier;
import net.schmizz.sshj.connection.Connection; import net.schmizz.sshj.connection.Connection;
import net.schmizz.sshj.connection.channel.SocketStreamCopyMonitor; import net.schmizz.sshj.connection.channel.SocketStreamCopyMonitor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
@@ -82,10 +82,10 @@ public class LocalPortForwarder {
throws IOException { throws IOException {
socket.setSendBufferSize(getLocalMaxPacketSize()); socket.setSendBufferSize(getLocalMaxPacketSize());
socket.setReceiveBufferSize(getRemoteMaxPacketSize()); socket.setReceiveBufferSize(getRemoteMaxPacketSize());
final Event<IOException> soc2chan = new StreamCopier(socket.getInputStream(), getOutputStream()) final Event<IOException> soc2chan = new StreamCopier(socket.getInputStream(), getOutputStream(), loggerFactory)
.bufSize(getRemoteMaxPacketSize()) .bufSize(getRemoteMaxPacketSize())
.spawnDaemon("soc2chan"); .spawnDaemon("soc2chan");
final Event<IOException> chan2soc = new StreamCopier(getInputStream(), socket.getOutputStream()) final Event<IOException> chan2soc = new StreamCopier(getInputStream(), socket.getOutputStream(), loggerFactory)
.bufSize(getLocalMaxPacketSize()) .bufSize(getLocalMaxPacketSize())
.spawnDaemon("chan2soc"); .spawnDaemon("chan2soc");
SocketStreamCopyMonitor.monitor(5, TimeUnit.SECONDS, soc2chan, chan2soc, this, socket); SocketStreamCopyMonitor.monitor(5, TimeUnit.SECONDS, soc2chan, chan2soc, this, socket);
@@ -102,16 +102,18 @@ public class LocalPortForwarder {
} }
private final Logger log = LoggerFactory.getLogger(LocalPortForwarder.class); private final LoggerFactory loggerFactory;
private final Logger log;
private final Connection conn; private final Connection conn;
private final Parameters parameters; private final Parameters parameters;
private final ServerSocket serverSocket; private final ServerSocket serverSocket;
public LocalPortForwarder(Connection conn, Parameters parameters, ServerSocket serverSocket) { public LocalPortForwarder(Connection conn, Parameters parameters, ServerSocket serverSocket, LoggerFactory loggerFactory) {
this.conn = conn; this.conn = conn;
this.parameters = parameters; this.parameters = parameters;
this.serverSocket = serverSocket; this.serverSocket = serverSocket;
this.loggerFactory = loggerFactory;
this.log = loggerFactory.getLogger(getClass());
} }
private void startChannel(Socket socket) throws IOException { private void startChannel(Socket socket) throws IOException {

View File

@@ -29,14 +29,14 @@ import java.io.IOException;
public abstract class AbstractForwardedChannelOpener public abstract class AbstractForwardedChannelOpener
implements ForwardedChannelOpener { implements ForwardedChannelOpener {
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final Logger log;
protected final String chanType; protected final String chanType;
protected final Connection conn; protected final Connection conn;
protected AbstractForwardedChannelOpener(String chanType, Connection conn) { protected AbstractForwardedChannelOpener(String chanType, Connection conn) {
this.chanType = chanType; this.chanType = chanType;
this.conn = conn; this.conn = conn;
log = conn.getTransport().getConfig().getLoggerFactory().getLogger(getClass());
} }
@Override @Override

View File

@@ -19,8 +19,6 @@ import net.schmizz.concurrent.Event;
import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.common.StreamCopier;
import net.schmizz.sshj.connection.channel.Channel; import net.schmizz.sshj.connection.channel.Channel;
import net.schmizz.sshj.connection.channel.SocketStreamCopyMonitor; import net.schmizz.sshj.connection.channel.SocketStreamCopyMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.Socket; import java.net.Socket;
@@ -31,8 +29,6 @@ import java.util.concurrent.TimeUnit;
public class SocketForwardingConnectListener public class SocketForwardingConnectListener
implements ConnectListener { implements ConnectListener {
protected final Logger log = LoggerFactory.getLogger(getClass());
protected final SocketAddress addr; protected final SocketAddress addr;
/** Create with a {@link SocketAddress} this listener will forward to. */ /** Create with a {@link SocketAddress} this listener will forward to. */
@@ -44,7 +40,7 @@ public class SocketForwardingConnectListener
@Override @Override
public void gotConnect(Channel.Forwarded chan) public void gotConnect(Channel.Forwarded chan)
throws IOException { throws IOException {
log.debug("New connection from {}:{}", chan.getOriginatorIP(), chan.getOriginatorPort()); chan.getLoggerFactory().getLogger(getClass()).debug("New connection from {}:{}", chan.getOriginatorIP(), chan.getOriginatorPort());
final Socket sock = new Socket(); final Socket sock = new Socket();
sock.setSendBufferSize(chan.getLocalMaxPacketSize()); sock.setSendBufferSize(chan.getLocalMaxPacketSize());
@@ -55,11 +51,11 @@ public class SocketForwardingConnectListener
// ok so far -- could connect, let's confirm the channel // ok so far -- could connect, let's confirm the channel
chan.confirm(); chan.confirm();
final Event<IOException> soc2chan = new StreamCopier(sock.getInputStream(), chan.getOutputStream()) final Event<IOException> soc2chan = new StreamCopier(sock.getInputStream(), chan.getOutputStream(), chan.getLoggerFactory())
.bufSize(chan.getRemoteMaxPacketSize()) .bufSize(chan.getRemoteMaxPacketSize())
.spawnDaemon("soc2chan"); .spawnDaemon("soc2chan");
final Event<IOException> chan2soc = new StreamCopier(chan.getInputStream(), sock.getOutputStream()) final Event<IOException> chan2soc = new StreamCopier(chan.getInputStream(), sock.getOutputStream(), chan.getLoggerFactory())
.bufSize(chan.getLocalMaxPacketSize()) .bufSize(chan.getLocalMaxPacketSize())
.spawnDaemon("chan2soc"); .spawnDaemon("chan2soc");

View File

@@ -29,7 +29,7 @@ public class PacketReader
extends Thread { extends Thread {
/** Logger */ /** Logger */
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
private final InputStream in; private final InputStream in;
private final Map<Long, Promise<Response, SFTPException>> promises = new ConcurrentHashMap<Long, Promise<Response, SFTPException>>(); private final Map<Long, Promise<Response, SFTPException>> promises = new ConcurrentHashMap<Long, Promise<Response, SFTPException>>();
@@ -39,6 +39,7 @@ public class PacketReader
public PacketReader(SFTPEngine engine) { public PacketReader(SFTPEngine engine) {
this.engine = engine; this.engine = engine;
log = engine.getLoggerFactory().getLogger(getClass());
this.in = engine.getSubsystem().getInputStream(); this.in = engine.getSubsystem().getInputStream();
setName("sftp reader"); setName("sftp reader");
} }
@@ -106,7 +107,7 @@ public class PacketReader
public Promise<Response, SFTPException> expectResponseTo(long requestId) { public Promise<Response, SFTPException> expectResponseTo(long requestId) {
final Promise<Response, SFTPException> promise final Promise<Response, SFTPException> promise
= new Promise<Response, SFTPException>("sftp / " + requestId, SFTPException.chainer); = new Promise<Response, SFTPException>("sftp / " + requestId, SFTPException.chainer, engine.getLoggerFactory());
promises.put(requestId, promise); promises.put(requestId, promise);
return promise; return promise;
} }

View File

@@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit;
public class RemoteDirectory public class RemoteDirectory
extends RemoteResource { extends RemoteResource {
public RemoteDirectory(Requester requester, String path, byte[] handle) { public RemoteDirectory(SFTPEngine requester, String path, byte[] handle) {
super(requester, path, handle); super(requester, path, handle);
} }

View File

@@ -30,7 +30,7 @@ import java.util.concurrent.TimeUnit;
public class RemoteFile public class RemoteFile
extends RemoteResource { extends RemoteResource {
public RemoteFile(Requester requester, String path, byte[] handle) { public RemoteFile(SFTPEngine requester, String path, byte[] handle) {
super(requester, path, handle); super(requester, path, handle);
} }

View File

@@ -26,14 +26,15 @@ public abstract class RemoteResource
implements Closeable { implements Closeable {
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final Logger log;
protected final Requester requester; protected final SFTPEngine requester;
protected final String path; protected final String path;
protected final byte[] handle; protected final byte[] handle;
protected RemoteResource(Requester requester, String path, byte[] handle) { protected RemoteResource(SFTPEngine requester, String path, byte[] handle) {
this.requester = requester; this.requester = requester;
log = requester.getLoggerFactory().getLogger(getClass());
this.path = path; this.path = path;
this.handle = handle; this.handle = handle;
} }

View File

@@ -29,13 +29,14 @@ public class SFTPClient
implements Closeable { implements Closeable {
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final Logger log;
protected final SFTPEngine engine; protected final SFTPEngine engine;
protected final SFTPFileTransfer xfer; protected final SFTPFileTransfer xfer;
public SFTPClient(SFTPEngine engine) { public SFTPClient(SFTPEngine engine) {
this.engine = engine; this.engine = engine;
log = engine.getLoggerFactory().getLogger(getClass());
this.xfer = new SFTPFileTransfer(engine); this.xfer = new SFTPFileTransfer(engine);
} }

View File

@@ -16,11 +16,11 @@
package net.schmizz.sshj.sftp; package net.schmizz.sshj.sftp;
import net.schmizz.concurrent.Promise; import net.schmizz.concurrent.Promise;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHException; import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.connection.channel.direct.Session.Subsystem; import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.SessionFactory; import net.schmizz.sshj.connection.channel.direct.SessionFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
@@ -38,13 +38,14 @@ public class SFTPEngine
public static final int DEFAULT_TIMEOUT_MS = 30 * 1000; // way too long, but it was the original default public static final int DEFAULT_TIMEOUT_MS = 30 * 1000; // way too long, but it was the original default
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final LoggerFactory loggerFactory;
protected final Logger log;
protected volatile int timeoutMs = DEFAULT_TIMEOUT_MS; protected volatile int timeoutMs = DEFAULT_TIMEOUT_MS;
protected final PathHelper pathHelper; protected final PathHelper pathHelper;
protected final Subsystem sub; protected final Session.Subsystem sub;
protected final PacketReader reader; protected final PacketReader reader;
protected final OutputStream out; protected final OutputStream out;
@@ -59,7 +60,10 @@ public class SFTPEngine
public SFTPEngine(SessionFactory ssh, String pathSep) public SFTPEngine(SessionFactory ssh, String pathSep)
throws SSHException { throws SSHException {
sub = ssh.startSession().startSubsystem("sftp"); Session session = ssh.startSession();
loggerFactory = session.getLoggerFactory();
log = loggerFactory.getLogger(getClass());
sub = session.startSubsystem("sftp");
out = sub.getOutputStream(); out = sub.getOutputStream();
reader = new PacketReader(this); reader = new PacketReader(this);
pathHelper = new PathHelper(new PathHelper.Canonicalizer() { pathHelper = new PathHelper(new PathHelper.Canonicalizer() {
@@ -94,7 +98,7 @@ public class SFTPEngine
return this; return this;
} }
public Subsystem getSubsystem() { public Session.Subsystem getSubsystem() {
return sub; return sub;
} }
@@ -248,6 +252,10 @@ public class SFTPEngine
reader.interrupt(); reader.interrupt();
} }
protected LoggerFactory getLoggerFactory() {
return loggerFactory;
}
protected FileAttributes stat(PacketType pt, String path) protected FileAttributes stat(PacketType pt, String path)
throws IOException { throws IOException {
return doRequest(newRequest(pt).putString(path)) return doRequest(newRequest(pt).putString(path))

View File

@@ -35,6 +35,7 @@ public class SFTPFileTransfer
private volatile boolean preserveAttributes = true; private volatile boolean preserveAttributes = true;
public SFTPFileTransfer(SFTPEngine engine) { public SFTPFileTransfer(SFTPEngine engine) {
super(engine.getLoggerFactory());
this.engine = engine; this.engine = engine;
} }
@@ -138,7 +139,7 @@ public class SFTPFileTransfer
final RemoteFile.ReadAheadRemoteFileInputStream rfis = rf.new ReadAheadRemoteFileInputStream(16); final RemoteFile.ReadAheadRemoteFileInputStream rfis = rf.new ReadAheadRemoteFileInputStream(16);
final OutputStream os = adjusted.getOutputStream(); final OutputStream os = adjusted.getOutputStream();
try { try {
new StreamCopier(rfis, os) new StreamCopier(rfis, os, engine.getLoggerFactory())
.bufSize(engine.getSubsystem().getLocalMaxPacketSize()) .bufSize(engine.getSubsystem().getLocalMaxPacketSize())
.keepFlushing(false) .keepFlushing(false)
.listener(listener) .listener(listener)
@@ -231,7 +232,7 @@ public class SFTPFileTransfer
try (RemoteFile rf = engine.open(adjusted, EnumSet.of(OpenMode.WRITE, OpenMode.CREAT, OpenMode.TRUNC))) { try (RemoteFile rf = engine.open(adjusted, EnumSet.of(OpenMode.WRITE, OpenMode.CREAT, OpenMode.TRUNC))) {
try (InputStream fis = local.getInputStream(); try (InputStream fis = local.getInputStream();
RemoteFile.RemoteFileOutputStream rfos = rf.new RemoteFileOutputStream(0, 16)) { RemoteFile.RemoteFileOutputStream rfos = rf.new RemoteFileOutputStream(0, 16)) {
new StreamCopier(fis, rfos) new StreamCopier(fis, rfos, engine.getLoggerFactory())
.bufSize(engine.getSubsystem().getRemoteMaxPacketSize() - rf.getOutgoingPacketOverhead()) .bufSize(engine.getSubsystem().getRemoteMaxPacketSize() - rf.getOutgoingPacketOverhead())
.keepFlushing(false) .keepFlushing(false)
.listener(listener) .listener(listener)

View File

@@ -16,6 +16,7 @@
package net.schmizz.sshj.transport; package net.schmizz.sshj.transport;
import net.schmizz.sshj.common.*; import net.schmizz.sshj.common.*;
import net.schmizz.sshj.transport.Transport;
import net.schmizz.sshj.transport.cipher.Cipher; import net.schmizz.sshj.transport.cipher.Cipher;
import net.schmizz.sshj.transport.compression.Compression; import net.schmizz.sshj.transport.compression.Compression;
import net.schmizz.sshj.transport.mac.MAC; import net.schmizz.sshj.transport.mac.MAC;
@@ -28,7 +29,7 @@ final class Decoder
private static final int MAX_PACKET_LEN = 256 * 1024; private static final int MAX_PACKET_LEN = 256 * 1024;
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
/** What we pass decoded packets to */ /** What we pass decoded packets to */
private final SSHPacketHandler packetHandler; private final SSHPacketHandler packetHandler;
@@ -48,8 +49,9 @@ final class Decoder
*/ */
private int needed = 8; private int needed = 8;
Decoder(SSHPacketHandler packetHandler) { Decoder(Transport packetHandler) {
this.packetHandler = packetHandler; this.packetHandler = packetHandler;
log = packetHandler.getConfig().getLoggerFactory().getLogger(getClass());
} }
/** /**

View File

@@ -15,13 +15,13 @@
*/ */
package net.schmizz.sshj.transport; package net.schmizz.sshj.transport;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher; import net.schmizz.sshj.transport.cipher.Cipher;
import net.schmizz.sshj.transport.compression.Compression; import net.schmizz.sshj.transport.compression.Compression;
import net.schmizz.sshj.transport.mac.MAC; import net.schmizz.sshj.transport.mac.MAC;
import net.schmizz.sshj.transport.random.Random; import net.schmizz.sshj.transport.random.Random;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
@@ -29,15 +29,14 @@ import java.util.concurrent.locks.Lock;
final class Encoder final class Encoder
extends Converter { extends Converter {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
private final Random prng; private final Random prng;
private final Lock encodeLock; private final Lock encodeLock;
Encoder(Random prng, Lock encodeLock) { Encoder(Random prng, Lock encodeLock, LoggerFactory loggerFactory) {
this.prng = prng; this.prng = prng;
this.encodeLock = encodeLock; this.encodeLock = encodeLock;
log = loggerFactory.getLogger(getClass());
} }
private SSHPacket checkHeaderSpace(SSHPacket buffer) { private SSHPacket checkHeaderSpace(SSHPacket buffer) {

View File

@@ -50,8 +50,7 @@ final class KeyExchanger
NEWKEYS, NEWKEYS,
} }
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
private final TransportImpl transport; private final TransportImpl transport;
/** /**
@@ -76,18 +75,20 @@ final class KeyExchanger
private Proposal clientProposal; private Proposal clientProposal;
private NegotiatedAlgorithms negotiatedAlgs; private NegotiatedAlgorithms negotiatedAlgs;
private final Event<TransportException> kexInitSent = private final Event<TransportException> kexInitSent;
new Event<TransportException>("kexinit sent", TransportException.chainer);
private final Event<TransportException> done; private final Event<TransportException> done;
KeyExchanger(TransportImpl trans) { KeyExchanger(TransportImpl trans) {
this.transport = trans; this.transport = trans;
log = trans.getConfig().getLoggerFactory().getLogger(getClass());
kexInitSent = new Event<TransportException>("kexinit sent", TransportException.chainer, trans.getConfig().getLoggerFactory());
/* /*
* Use TransportImpl's writeLock, since TransportImpl.write() may wait on this event and the lock should * Use TransportImpl's writeLock, since TransportImpl.write() may wait on this event and the lock should
* be released while waiting. * be released while waiting.
*/ */
this.done = new Event<TransportException>("kex done", TransportException.chainer, trans.getWriteLock()); this.done = new Event<TransportException>("kex done", TransportException.chainer, trans.getWriteLock(), trans.getConfig().getLoggerFactory());
} }
/** /**

View File

@@ -24,12 +24,12 @@ import java.net.SocketTimeoutException;
public final class Reader public final class Reader
extends Thread { extends Thread {
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log;
private final TransportImpl trans; private final TransportImpl trans;
public Reader(TransportImpl trans) { public Reader(TransportImpl trans) {
this.trans = trans; this.trans = trans;
log = trans.getConfig().getLoggerFactory().getLogger(getClass());
setName("reader"); setName("reader");
} }

View File

@@ -18,6 +18,7 @@ package net.schmizz.sshj.transport;
import net.schmizz.sshj.Config; import net.schmizz.sshj.Config;
import net.schmizz.sshj.Service; import net.schmizz.sshj.Service;
import net.schmizz.sshj.common.DisconnectReason; import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.common.SSHPacketHandler; import net.schmizz.sshj.common.SSHPacketHandler;
import net.schmizz.sshj.transport.verification.AlgorithmsVerifier; import net.schmizz.sshj.transport.verification.AlgorithmsVerifier;

View File

@@ -26,7 +26,6 @@ import net.schmizz.sshj.common.*;
import net.schmizz.sshj.transport.verification.AlgorithmsVerifier; import net.schmizz.sshj.transport.verification.AlgorithmsVerifier;
import net.schmizz.sshj.transport.verification.HostKeyVerifier; import net.schmizz.sshj.transport.verification.HostKeyVerifier;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -36,7 +35,7 @@ import java.util.concurrent.locks.ReentrantLock;
/** A thread-safe {@link Transport} implementation. */ /** A thread-safe {@link Transport} implementation. */
public final class TransportImpl public final class TransportImpl
implements Transport { implements Transport, DisconnectListener {
private static final class NullService private static final class NullService
extends AbstractService { extends AbstractService {
@@ -46,6 +45,7 @@ public final class TransportImpl
} }
} }
static final class ConnInfo { static final class ConnInfo {
final String host; final String host;
@@ -61,16 +61,12 @@ public final class TransportImpl
} }
} }
private final Logger log = LoggerFactory.getLogger(getClass());
private final Service nullService = new NullService(this); private final LoggerFactory loggerFactory;
private final DisconnectListener nullDisconnectListener = new DisconnectListener() { private final Logger log;
@Override
public void notifyDisconnect(DisconnectReason reason, String message) { private final Service nullService;
log.info("Disconnected - {}", reason);
}
};
private final Config config; private final Config config;
@@ -88,9 +84,9 @@ public final class TransportImpl
private final Decoder decoder; private final Decoder decoder;
private final Event<TransportException> serviceAccept = new Event<TransportException>("service accept", TransportException.chainer); private final Event<TransportException> serviceAccept;
private final Event<TransportException> close = new Event<TransportException>("transport close", TransportException.chainer); private final Event<TransportException> close;
/** Client version identification string */ /** Client version identification string */
private final String clientID; private final String clientID;
@@ -100,9 +96,9 @@ public final class TransportImpl
private volatile boolean authed = false; private volatile boolean authed = false;
/** Currently active service e.g. UserAuthService, ConnectionService */ /** Currently active service e.g. UserAuthService, ConnectionService */
private volatile Service service = nullService; private volatile Service service;
private DisconnectListener disconnectListener = nullDisconnectListener; private DisconnectListener disconnectListener;
private ConnInfo connInfo; private ConnInfo connInfo;
@@ -116,8 +112,15 @@ public final class TransportImpl
public TransportImpl(Config config) { public TransportImpl(Config config) {
this.config = config; this.config = config;
this.loggerFactory = config.getLoggerFactory();
this.serviceAccept = new Event<TransportException>("service accept", TransportException.chainer, loggerFactory);
this.close = new Event<TransportException>("transport close", TransportException.chainer, loggerFactory);
this.nullService = new NullService(this);
this.service = nullService;
this.log = loggerFactory.getLogger(getClass());
this.disconnectListener = this;
this.reader = new Reader(this); this.reader = new Reader(this);
this.encoder = new Encoder(config.getRandomFactory().create(), writeLock); this.encoder = new Encoder(config.getRandomFactory().create(), writeLock, loggerFactory);
this.decoder = new Decoder(this); this.decoder = new Decoder(this);
this.kexer = new KeyExchanger(this); this.kexer = new KeyExchanger(this);
this.clientID = String.format("SSH-2.0-%s", config.getVersion()); this.clientID = String.format("SSH-2.0-%s", config.getVersion());
@@ -131,16 +134,21 @@ public final class TransportImpl
@Deprecated @Deprecated
public TransportImpl(Config config, SSHClient sshClient) { public TransportImpl(Config config, SSHClient sshClient) {
this.config = config; this.config = config;
this.loggerFactory = config.getLoggerFactory();
this.serviceAccept = new Event<TransportException>("service accept", TransportException.chainer, loggerFactory);
this.close = new Event<TransportException>("transport close", TransportException.chainer, loggerFactory);
this.log = loggerFactory.getLogger(getClass());
this.nullService = new NullService(this);
this.service = nullService;
this.disconnectListener = this;
this.reader = new Reader(this); this.reader = new Reader(this);
this.encoder = new Encoder(config.getRandomFactory().create(), writeLock); this.encoder = new Encoder(config.getRandomFactory().create(), writeLock, loggerFactory);
this.decoder = new Decoder(this); this.decoder = new Decoder(this);
this.kexer = new KeyExchanger(this); this.kexer = new KeyExchanger(this);
this.clientID = String.format("SSH-2.0-%s", config.getVersion()); this.clientID = String.format("SSH-2.0-%s", config.getVersion());
this.sshClient = sshClient; this.sshClient = sshClient;
} }
@Override @Override
public void init(String remoteHost, int remotePort, InputStream in, OutputStream out) public void init(String remoteHost, int remotePort, InputStream in, OutputStream out)
throws TransportException { throws TransportException {
@@ -166,6 +174,14 @@ public final class TransportImpl
reader.start(); reader.start();
} }
/**
* TransportImpl implements its own default DisconnectListener.
*/
@Override
public void notifyDisconnect(DisconnectReason reason, String message) {
log.info("Disconnected - {}", reason);
}
private void receiveServerIdent() throws IOException { private void receiveServerIdent() throws IOException {
final Buffer.PlainBuffer buf = new Buffer.PlainBuffer(); final Buffer.PlainBuffer buf = new Buffer.PlainBuffer();
while ((serverID = readIdentification(buf)).isEmpty()) { while ((serverID = readIdentification(buf)).isEmpty()) {
@@ -203,7 +219,7 @@ public final class TransportImpl
*/ */
private String readIdentification(Buffer.PlainBuffer buffer) private String readIdentification(Buffer.PlainBuffer buffer)
throws IOException { throws IOException {
String ident = new IdentificationStringParser(buffer).parseIdentificationString(); String ident = new IdentificationStringParser(loggerFactory, buffer).parseIdentificationString();
if (ident.isEmpty()) { if (ident.isEmpty()) {
return ident; return ident;
} }
@@ -432,7 +448,7 @@ public final class TransportImpl
@Override @Override
public void setDisconnectListener(DisconnectListener listener) { public void setDisconnectListener(DisconnectListener listener) {
this.disconnectListener = listener == null ? nullDisconnectListener : listener; this.disconnectListener = listener == null ? this : listener;
} }
@Override @Override

View File

@@ -19,7 +19,6 @@ import net.schmizz.sshj.common.*;
import net.schmizz.sshj.transport.mac.HMACSHA1; import net.schmizz.sshj.transport.mac.HMACSHA1;
import net.schmizz.sshj.transport.mac.MAC; import net.schmizz.sshj.transport.mac.MAC;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
@@ -38,23 +37,29 @@ import java.util.List;
public class OpenSSHKnownHosts public class OpenSSHKnownHosts
implements HostKeyVerifier { implements HostKeyVerifier {
private static final Logger LOG = LoggerFactory.getLogger(OpenSSHKnownHosts.class); protected final Logger log;
protected final Logger log = LoggerFactory.getLogger(getClass());
protected final File khFile; protected final File khFile;
protected final List<HostEntry> entries = new ArrayList<HostEntry>(); protected final List<HostEntry> entries = new ArrayList<HostEntry>();
public OpenSSHKnownHosts(File khFile) public OpenSSHKnownHosts(File khFile)
throws IOException { throws IOException {
this(khFile, LoggerFactory.DEFAULT);
}
public OpenSSHKnownHosts(File khFile, LoggerFactory loggerFactory)
throws IOException {
this.khFile = khFile; this.khFile = khFile;
log = loggerFactory.getLogger(getClass());
if (khFile.exists()) { if (khFile.exists()) {
final EntryFactory entryFactory = new EntryFactory();
final BufferedReader br = new BufferedReader(new FileReader(khFile)); final BufferedReader br = new BufferedReader(new FileReader(khFile));
try { try {
// Read in the file, storing each line as an entry // Read in the file, storing each line as an entry
String line; String line;
while ((line = br.readLine()) != null) while ((line = br.readLine()) != null)
try { try {
HostEntry entry = EntryFactory.parseEntry(line); HostEntry entry = entryFactory.parseEntry(line);
if (entry != null) { if (entry != null) {
entries.add(entry); entries.add(entry);
} }
@@ -173,9 +178,11 @@ public class OpenSSHKnownHosts
* <p/> * <p/>
* Lines starting with `#' and empty lines are ignored as comments. * Lines starting with `#' and empty lines are ignored as comments.
*/ */
public static class EntryFactory { public class EntryFactory {
EntryFactory() {
}
public static HostEntry parseEntry(String line) public HostEntry parseEntry(String line)
throws IOException { throws IOException {
if (isComment(line)) { if (isComment(line)) {
return new CommentEntry(line); return new CommentEntry(line);
@@ -189,7 +196,7 @@ public class OpenSSHKnownHosts
i++; i++;
} }
if(split.length < 3) { if(split.length < 3) {
LOG.error("Error reading entry `{}`", line); log.error("Error reading entry `{}`", line);
return null; return null;
} }
final String hostnames = split[i++]; final String hostnames = split[i++];
@@ -210,11 +217,11 @@ public class OpenSSHKnownHosts
final KeyFactory keyFactory = SecurityUtils.getKeyFactory("RSA"); final KeyFactory keyFactory = SecurityUtils.getKeyFactory("RSA");
key = keyFactory.generatePublic(new RSAPublicKeySpec(n, e)); key = keyFactory.generatePublic(new RSAPublicKeySpec(n, e));
} catch (Exception ex) { } catch (Exception ex) {
LOG.error("Error reading entry `{}`, could not create key", line, ex); log.error("Error reading entry `{}`, could not create key", line, ex);
return null; return null;
} }
} else { } else {
LOG.error("Error reading entry `{}`, could not determine type", line); log.error("Error reading entry `{}`, could not determine type", line);
return null; return null;
} }
@@ -225,12 +232,12 @@ public class OpenSSHKnownHosts
} }
} }
private static PublicKey getKey(String sKey) private PublicKey getKey(String sKey)
throws IOException { throws IOException {
return new Buffer.PlainBuffer(Base64.decode(sKey)).readPublicKey(); return new Buffer.PlainBuffer(Base64.decode(sKey)).readPublicKey();
} }
private static boolean isBits(String type) { private boolean isBits(String type) {
try { try {
Integer.parseInt(type); Integer.parseInt(type);
return true; return true;
@@ -239,11 +246,11 @@ public class OpenSSHKnownHosts
} }
} }
private static boolean isComment(String line) { private boolean isComment(String line) {
return line.isEmpty() || line.startsWith("#"); return line.isEmpty() || line.startsWith("#");
} }
public static boolean isHashed(String line) { public boolean isHashed(String line) {
return line.startsWith("|1|"); return line.startsWith("|1|");
} }

View File

@@ -37,8 +37,7 @@ public class UserAuthImpl
extends AbstractService extends AbstractService
implements UserAuth { implements UserAuth {
private final Promise<Boolean, UserAuthException> authenticated private final Promise<Boolean, UserAuthException> authenticated;
= new Promise<Boolean, UserAuthException>("authenticated", UserAuthException.chainer);
// Externally available // Externally available
private volatile String banner = ""; private volatile String banner = "";
@@ -51,6 +50,7 @@ public class UserAuthImpl
public UserAuthImpl(Transport trans) { public UserAuthImpl(Transport trans) {
super("ssh-userauth", trans); super("ssh-userauth", trans);
authenticated = new Promise<Boolean, UserAuthException>("authenticated", UserAuthException.chainer, trans.getConfig().getLoggerFactory());
} }
@Override @Override

View File

@@ -15,6 +15,7 @@
*/ */
package net.schmizz.sshj.userauth.method; package net.schmizz.sshj.userauth.method;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.Message; import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHPacket; import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.transport.TransportException;
@@ -22,14 +23,13 @@ import net.schmizz.sshj.userauth.AuthParams;
import net.schmizz.sshj.userauth.UserAuthException; import net.schmizz.sshj.userauth.UserAuthException;
import net.schmizz.sshj.userauth.password.AccountResource; import net.schmizz.sshj.userauth.password.AccountResource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** This abstract class for {@link AuthMethod} implements common or default functionality. */ /** This abstract class for {@link AuthMethod} implements common or default functionality. */
public abstract class AbstractAuthMethod public abstract class AbstractAuthMethod
implements AuthMethod { implements AuthMethod {
/** Logger */ /** Logger */
protected final Logger log = LoggerFactory.getLogger(getClass()); protected Logger log = org.slf4j.LoggerFactory.getLogger(getClass());
private final String name; private final String name;
@@ -41,6 +41,11 @@ public abstract class AbstractAuthMethod
this.name = name; this.name = name;
} }
@Override
public void setLoggerFactory(LoggerFactory loggerFactory) {
log = loggerFactory.getLogger(getClass());
}
@Override @Override
public String getName() { public String getName() {
return name; return name;

View File

@@ -15,6 +15,7 @@
*/ */
package net.schmizz.sshj.userauth.method; package net.schmizz.sshj.userauth.method;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHPacketHandler; import net.schmizz.sshj.common.SSHPacketHandler;
import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.userauth.AuthParams; import net.schmizz.sshj.userauth.AuthParams;
@@ -44,4 +45,5 @@ public interface AuthMethod
/** @return whether authentication should be reattempted if it failed. */ /** @return whether authentication should be reattempted if it failed. */
boolean shouldRetry(); boolean shouldRetry();
void setLoggerFactory(LoggerFactory loggerFactory);
} }

View File

@@ -15,10 +15,10 @@
*/ */
package net.schmizz.sshj.userauth.method; package net.schmizz.sshj.userauth.method;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.userauth.password.PasswordFinder; import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.Resource; import net.schmizz.sshj.userauth.password.Resource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -29,12 +29,11 @@ public class PasswordResponseProvider
public static final Pattern DEFAULT_PROMPT_PATTERN = Pattern.compile(".*[pP]assword:\\s?\\z", Pattern.DOTALL); public static final Pattern DEFAULT_PROMPT_PATTERN = Pattern.compile(".*[pP]assword:\\s?\\z", Pattern.DOTALL);
private final Logger log = LoggerFactory.getLogger(getClass());
private static final char[] EMPTY_RESPONSE = new char[0]; private static final char[] EMPTY_RESPONSE = new char[0];
private final Pattern promptPattern; private final Pattern promptPattern;
private final PasswordFinder pwdf; private final PasswordFinder pwdf;
private final Logger log;
private Resource resource; private Resource resource;
@@ -43,8 +42,13 @@ public class PasswordResponseProvider
} }
public PasswordResponseProvider(PasswordFinder pwdf, Pattern promptPattern) { public PasswordResponseProvider(PasswordFinder pwdf, Pattern promptPattern) {
this(pwdf, promptPattern, LoggerFactory.DEFAULT);
}
public PasswordResponseProvider(PasswordFinder pwdf, Pattern promptPattern, LoggerFactory loggerFactory) {
this.pwdf = pwdf; this.pwdf = pwdf;
this.promptPattern = promptPattern; this.promptPattern = promptPattern;
log = loggerFactory.getLogger(getClass());
} }
@Override @Override

View File

@@ -15,23 +15,32 @@
*/ */
package net.schmizz.sshj.xfer; package net.schmizz.sshj.xfer;
import net.schmizz.sshj.common.LoggerFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractFileTransfer { public abstract class AbstractFileTransfer {
protected final Logger log = LoggerFactory.getLogger(getClass()); protected final LoggerFactory loggerFactory;
protected final Logger log;
public static final LoggingTransferListener LOGGING_TRANSFER_LISTENER = new LoggingTransferListener(); private final LoggingTransferListener loggingTransferListener;
private volatile TransferListener transferListener = LOGGING_TRANSFER_LISTENER; private volatile TransferListener transferListener;
protected AbstractFileTransfer(LoggerFactory loggerFactory) {
this.loggerFactory = loggerFactory;
log = loggerFactory.getLogger(getClass());
loggingTransferListener = new LoggingTransferListener(loggerFactory);
transferListener = loggingTransferListener;
}
public TransferListener getTransferListener() { public TransferListener getTransferListener() {
return transferListener; return transferListener;
} }
public void setTransferListener(TransferListener transferListener) { public void setTransferListener(TransferListener transferListener) {
this.transferListener = (transferListener == null) ? LOGGING_TRANSFER_LISTENER : transferListener; this.transferListener = (transferListener == null) ? loggingTransferListener : transferListener;
} }
} }

View File

@@ -15,31 +15,34 @@
*/ */
package net.schmizz.sshj.xfer; package net.schmizz.sshj.xfer;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.common.StreamCopier;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
public class LoggingTransferListener public class LoggingTransferListener
implements TransferListener { implements TransferListener {
private final Logger log = LoggerFactory.getLogger(getClass()); private final LoggerFactory loggerFactory;
private final Logger log;
private final String relPath; private final String relPath;
public LoggingTransferListener() { public LoggingTransferListener(LoggerFactory loggerFactory) {
this(""); this("", loggerFactory);
} }
private LoggingTransferListener(String relPath) { private LoggingTransferListener(String relPath, LoggerFactory loggerFactory) {
this.relPath = relPath; this.relPath = relPath;
this.loggerFactory = loggerFactory;
log = loggerFactory.getLogger(getClass());
} }
@Override @Override
public TransferListener directory(String name) { public TransferListener directory(String name) {
log.debug("started transferring directory `{}`", name); log.debug("started transferring directory `{}`", name);
return new LoggingTransferListener(relPath + name + "/"); return new LoggingTransferListener(relPath + name + "/", loggerFactory);
} }
@Override @Override

View File

@@ -16,13 +16,13 @@
package net.schmizz.sshj.xfer.scp; package net.schmizz.sshj.xfer.scp;
import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHException; import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.common.StreamCopier;
import net.schmizz.sshj.connection.channel.direct.Session.Command; import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.connection.channel.direct.SessionFactory; import net.schmizz.sshj.connection.channel.direct.SessionFactory;
import net.schmizz.sshj.xfer.TransferListener; import net.schmizz.sshj.xfer.TransferListener;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@@ -35,7 +35,8 @@ class SCPEngine {
private static final char LF = '\n'; private static final char LF = '\n';
private final Logger log = LoggerFactory.getLogger(getClass()); private final LoggerFactory loggerFactory;
private final Logger log;
private final SessionFactory host; private final SessionFactory host;
private final TransferListener listener; private final TransferListener listener;
@@ -43,9 +44,11 @@ class SCPEngine {
private Command scp; private Command scp;
private int exitStatus; private int exitStatus;
SCPEngine(SessionFactory host, TransferListener listener) { SCPEngine(SessionFactory host, TransferListener listener, LoggerFactory loggerFactory) {
this.host = host; this.host = host;
this.listener = listener; this.listener = listener;
this.loggerFactory = loggerFactory;
log = loggerFactory.getLogger(getClass());
} }
public int getExitStatus() { public int getExitStatus() {
@@ -57,7 +60,7 @@ class SCPEngine {
int code = scp.getInputStream().read(); int code = scp.getInputStream().read();
switch (code) { switch (code) {
case -1: case -1:
String stderr = IOUtils.readFully(scp.getErrorStream()).toString(); String stderr = IOUtils.readFully(scp.getErrorStream(), loggerFactory).toString();
if (!stderr.isEmpty()) if (!stderr.isEmpty())
stderr = ". Additional info: `" + stderr + "`"; stderr = ". Additional info: `" + stderr + "`";
throw new SCPException("EOF while expecting response to protocol message" + stderr); throw new SCPException("EOF while expecting response to protocol message" + stderr);
@@ -137,7 +140,7 @@ class SCPEngine {
} }
long transferToRemote(StreamCopier.Listener listener, InputStream src, long length) throws IOException { long transferToRemote(StreamCopier.Listener listener, InputStream src, long length) throws IOException {
return new StreamCopier(src, scp.getOutputStream()) return new StreamCopier(src, scp.getOutputStream(), loggerFactory)
.bufSize(scp.getRemoteMaxPacketSize()).length(length) .bufSize(scp.getRemoteMaxPacketSize()).length(length)
.keepFlushing(false) .keepFlushing(false)
.listener(listener) .listener(listener)
@@ -145,7 +148,7 @@ class SCPEngine {
} }
long transferFromRemote(StreamCopier.Listener listener, OutputStream dest, long length) throws IOException { long transferFromRemote(StreamCopier.Listener listener, OutputStream dest, long length) throws IOException {
return new StreamCopier(scp.getInputStream(), dest) return new StreamCopier(scp.getInputStream(), dest, loggerFactory)
.bufSize(scp.getLocalMaxPacketSize()).length(length) .bufSize(scp.getLocalMaxPacketSize()).length(length)
.keepFlushing(false) .keepFlushing(false)
.listener(listener) .listener(listener)

View File

@@ -15,6 +15,7 @@
*/ */
package net.schmizz.sshj.xfer.scp; package net.schmizz.sshj.xfer.scp;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.connection.channel.direct.SessionFactory; import net.schmizz.sshj.connection.channel.direct.SessionFactory;
import net.schmizz.sshj.xfer.*; import net.schmizz.sshj.xfer.*;
@@ -30,7 +31,8 @@ public class SCPFileTransfer
private final SessionFactory sessionFactory; private final SessionFactory sessionFactory;
private int bandwidthLimit; private int bandwidthLimit;
public SCPFileTransfer(SessionFactory sessionFactory) { public SCPFileTransfer(SessionFactory sessionFactory, LoggerFactory loggerFactory) {
super(loggerFactory);
this.sessionFactory = sessionFactory; this.sessionFactory = sessionFactory;
this.bandwidthLimit = DEFAULT_BANDWIDTH_LIMIT; this.bandwidthLimit = DEFAULT_BANDWIDTH_LIMIT;
} }
@@ -44,7 +46,7 @@ public class SCPFileTransfer
} }
private SCPEngine newSCPEngine() { private SCPEngine newSCPEngine() {
return new SCPEngine(sessionFactory, getTransferListener()); return new SCPEngine(sessionFactory, getTransferListener(), loggerFactory);
} }
@Override @Override