You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2015/08/25 06:38:18 UTC

[4/4] mina-sshd git commit: [SSHD-555] Add ChannelListener support

[SSHD-555] Add ChannelListener support


Project: http://git-wip-us.apache.org/repos/asf/mina-sshd/repo
Commit: http://git-wip-us.apache.org/repos/asf/mina-sshd/commit/40195ab4
Tree: http://git-wip-us.apache.org/repos/asf/mina-sshd/tree/40195ab4
Diff: http://git-wip-us.apache.org/repos/asf/mina-sshd/diff/40195ab4

Branch: refs/heads/master
Commit: 40195ab466bb7ae97fd88c21b9a3394e78566ba9
Parents: 051aec3
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Tue Aug 25 07:38:01 2015 +0300
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Tue Aug 25 07:38:01 2015 +0300

----------------------------------------------------------------------
 .../agent/local/ChannelAgentForwarding.java     |  22 +-
 .../sshd/agent/unix/AgentForwardedChannel.java  |   2 -
 .../sshd/agent/unix/ChannelAgentForwarding.java |  35 +-
 .../org/apache/sshd/client/SessionFactory.java  |  46 -
 .../java/org/apache/sshd/client/SshClient.java  |  13 +-
 .../java/org/apache/sshd/client/SshKeyScan.java |   4 +-
 .../client/channel/AbstractClientChannel.java   |  15 +-
 .../sshd/client/channel/ChannelSession.java     |   1 -
 .../sshd/client/session/ClientSession.java      |   1 -
 .../sshd/client/session/ClientSessionImpl.java  |   4 +-
 .../client/session/ClientUserAuthService.java   |   4 +-
 .../sshd/client/session/SessionFactory.java     |  46 +
 .../sshd/client/subsystem/SubsystemClient.java  |   6 +
 .../subsystem/sftp/DefaultSftpClient.java       |   6 +
 .../client/subsystem/sftp/SftpFileSystem.java   |   6 +
 .../sshd/common/AbstractFactoryManager.java     |  99 ++-
 .../org/apache/sshd/common/FactoryManager.java  |   4 +-
 .../sshd/common/channel/AbstractChannel.java    |  94 +-
 .../org/apache/sshd/common/channel/Channel.java |   6 +-
 .../common/channel/ChannelAsyncInputStream.java |   4 +
 .../sshd/common/channel/ChannelListener.java    |  74 ++
 .../common/channel/ChannelListenerManager.java  |  47 +
 .../common/channel/ChannelPipedInputStream.java |  25 +-
 .../sshd/common/future/DefaultSshFuture.java    |  17 +-
 .../sshd/common/session/AbstractSession.java    | 168 ++--
 .../common/session/AbstractSessionFactory.java  |  55 +-
 .../org/apache/sshd/common/session/Session.java |  17 +-
 .../common/session/SessionListenerManager.java  |  53 ++
 .../common/session/SessionTimeoutListener.java  |  17 +-
 .../sshd/common/util/EventListenerUtils.java    |  23 +-
 .../apache/sshd/common/util/GenericUtils.java   |  46 +
 .../sshd/server/ServerFactoryManager.java       |   1 -
 .../java/org/apache/sshd/server/SshServer.java  |   3 +-
 .../auth/CachingPublicKeyAuthenticator.java     |   2 +-
 .../server/channel/AbstractServerChannel.java   |  18 +-
 .../sshd/server/channel/ChannelSession.java     |  11 +-
 .../sshd/server/forward/TcpipServerChannel.java |  74 +-
 .../sshd/server/session/SessionFactory.java     |  24 +-
 .../org/apache/sshd/AuthenticationTest.java     |   5 +-
 .../java/org/apache/sshd/KeepAliveTest.java     |  79 +-
 .../java/org/apache/sshd/KeyReExchangeTest.java |   2 +-
 .../java/org/apache/sshd/client/ClientTest.java | 874 +++++++++++++------
 .../common/channel/TestChannelListener.java     |  95 ++
 .../sshd/common/io/nio2/Nio2ServiceTest.java    |   1 -
 .../AbstractSignatureFactoryTestSupport.java    |   1 -
 .../deprecated/ClientUserAuthServiceOld.java    |   2 +-
 .../sshd/server/PublickeyAuthenticatorTest.java |   2 +-
 .../java/org/apache/sshd/server/ServerTest.java | 224 ++---
 .../java/org/apache/sshd/git/util/Utils.java    |   2 +-
 49 files changed, 1638 insertions(+), 742 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/agent/local/ChannelAgentForwarding.java
----------------------------------------------------------------------
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 a93d12b..19baa6b 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
@@ -22,13 +22,18 @@ import java.io.IOException;
 import java.io.OutputStream;
 
 import org.apache.sshd.agent.SshAgent;
+import org.apache.sshd.agent.SshAgentFactory;
 import org.apache.sshd.agent.common.AbstractAgentClient;
 import org.apache.sshd.client.future.DefaultOpenFuture;
 import org.apache.sshd.client.future.OpenFuture;
+import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.common.SshConstants;
+import org.apache.sshd.common.channel.ChannelListener;
 import org.apache.sshd.common.channel.ChannelOutputStream;
 import org.apache.sshd.common.future.CloseFuture;
 import org.apache.sshd.common.future.SshFutureListener;
+import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
 import org.apache.sshd.server.channel.AbstractServerChannel;
@@ -48,13 +53,24 @@ public class ChannelAgentForwarding extends AbstractServerChannel {
     @Override
     protected OpenFuture doInit(Buffer buffer) {
         final OpenFuture f = new DefaultOpenFuture(this);
+        ChannelListener listener = getChannelListenerProxy();
         try {
             out = new ChannelOutputStream(this, remoteWindow, log, SshConstants.SSH_MSG_CHANNEL_DATA);
-            agent = session.getFactoryManager().getAgentFactory().createClient(session.getFactoryManager());
+            FactoryManager manager = session.getFactoryManager();
+            SshAgentFactory factory = ValidateUtils.checkNotNull(manager.getAgentFactory(), "No agent factory");
+            agent = factory.createClient(manager);
             client = new AgentClient();
-            f.setOpened();
 
-        } catch (Exception e) {
+            listener.channelOpenSuccess(this);
+            f.setOpened();
+        } catch (Throwable t) {
+            Throwable e = GenericUtils.peelException(t);
+            try {
+                listener.channelOpenFailure(this, e);
+            } catch (Throwable ignored) {
+                log.warn("doInit({}) failed ({}) to inform listener of open failure={}: {}",
+                         this, ignored.getClass().getSimpleName(), e.getClass().getSimpleName(), ignored.getMessage());
+            }
             f.setException(e);
         }
         return f;

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentForwardedChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentForwardedChannel.java b/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentForwardedChannel.java
index eb33231..8ed5c07 100644
--- a/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentForwardedChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentForwardedChannel.java
@@ -77,7 +77,5 @@ public class AgentForwardedChannel extends AbstractClientChannel implements Runn
         if (result < Status.APR_SUCCESS) {
             AgentServerProxy.throwException(result);
         }
-
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/agent/unix/ChannelAgentForwarding.java
----------------------------------------------------------------------
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 1cccc8f..113f33d 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
@@ -29,10 +29,12 @@ import org.apache.sshd.client.future.DefaultOpenFuture;
 import org.apache.sshd.client.future.OpenFuture;
 import org.apache.sshd.common.FactoryManagerUtils;
 import org.apache.sshd.common.SshConstants;
+import org.apache.sshd.common.channel.ChannelListener;
 import org.apache.sshd.common.channel.ChannelOutputStream;
 import org.apache.sshd.common.future.CloseFuture;
 import org.apache.sshd.common.future.SshFutureListener;
 import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.threads.ThreadUtils;
 import org.apache.sshd.server.channel.AbstractServerChannel;
@@ -45,6 +47,18 @@ import org.apache.tomcat.jni.Status;
  * The client side channel that will receive requests forwards by the SSH server.
  */
 public class ChannelAgentForwarding extends AbstractServerChannel {
+    /**
+     * Property that can be set on the factory manager in order to control
+     * the buffer size used to forward data from the established channel
+     *
+     * @see #MIN_FORWARDER_BUF_SIZE
+     * @see #MAX_FORWARDER_BUF_SIZE
+     * @see #DEFAULT_FORWARDER_BUF_SIZE
+     */
+    public static final String FORWARDER_BUFFER_SIZE = "channel-agent-fwd-buf-size";
+    public static final int MIN_FORWARDER_BUF_SIZE = Byte.MAX_VALUE;
+    public static final int DEFAULT_FORWARDER_BUF_SIZE = 1024;
+    public static final int MAX_FORWARDER_BUF_SIZE = Short.MAX_VALUE;
 
     private String authSocket;
     private long pool;
@@ -61,6 +75,7 @@ public class ChannelAgentForwarding extends AbstractServerChannel {
     @Override
     protected OpenFuture doInit(Buffer buffer) {
         final OpenFuture f = new DefaultOpenFuture(this);
+        ChannelListener listener = getChannelListenerProxy();
         try {
             out = new ChannelOutputStream(this, remoteWindow, log, SshConstants.SSH_MSG_CHANNEL_DATA);
             authSocket = FactoryManagerUtils.getString(session, SshAgent.SSH_AUTHSOCKET_ENV_NAME);
@@ -74,12 +89,17 @@ public class ChannelAgentForwarding extends AbstractServerChannel {
             ExecutorService service = getExecutorService();
             forwardService = (service == null) ? ThreadUtils.newSingleThreadExecutor("ChannelAgentForwarding[" + authSocket + "]") : service;
             shutdownForwarder = (service == forwardService) ? isShutdownOnExit() : true;
+
+            final int copyBufSize = FactoryManagerUtils.getIntProperty(getSession(), 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);
+
             forwarder = forwardService.submit(new Runnable() {
                 @SuppressWarnings("synthetic-access")
                 @Override
                 public void run() {
                     try {
-                        byte[] buf = new byte[1024];
+                        byte[] buf = new byte[copyBufSize];
                         while (true) {
                             int len = Socket.recv(handle, buf, 0, buf.length);
                             if (len > 0) {
@@ -92,11 +112,20 @@ public class ChannelAgentForwarding extends AbstractServerChannel {
                     }
                 }
             });
-            f.setOpened();
 
-        } catch (Exception e) {
+            listener.channelOpenSuccess(this);
+            f.setOpened();
+        } catch (Exception t) {
+            Throwable e = GenericUtils.peelException(t);
+            try {
+                listener.channelOpenFailure(this, e);
+            } catch (Throwable ignored) {
+                log.warn("doInit({}) failed ({}) to inform listener of open failure={}: {}",
+                         this, ignored.getClass().getSimpleName(), e.getClass().getSimpleName(), ignored.getMessage());
+            }
             f.setException(e);
         }
+
         return f;
     }
 

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/SessionFactory.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SessionFactory.java b/sshd-core/src/main/java/org/apache/sshd/client/SessionFactory.java
deleted file mode 100644
index 76527a2..0000000
--- a/sshd-core/src/main/java/org/apache/sshd/client/SessionFactory.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.sshd.client;
-
-import org.apache.sshd.client.session.ClientSessionImpl;
-import org.apache.sshd.common.io.IoSession;
-import org.apache.sshd.common.session.AbstractSession;
-import org.apache.sshd.common.session.AbstractSessionFactory;
-
-/**
- * A factory of client sessions.
- * This class can be used as a way to customize the creation of client sessions.
- *
- * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
- * @see org.apache.sshd.client.SshClient#setSessionFactory(SessionFactory)
- */
-public class SessionFactory extends AbstractSessionFactory {
-
-    protected ClientFactoryManager client;
-
-    public void setClient(ClientFactoryManager client) {
-        this.client = client;
-    }
-
-    @Override
-    protected AbstractSession doCreateSession(IoSession ioSession) throws Exception {
-        return new ClientSessionImpl(client, ioSession);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
----------------------------------------------------------------------
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 c98ce14..6e21329 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
@@ -55,6 +55,7 @@ import org.apache.sshd.client.future.DefaultConnectFuture;
 import org.apache.sshd.client.session.ClientConnectionServiceFactory;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.client.session.ClientUserAuthServiceFactory;
+import org.apache.sshd.client.session.SessionFactory;
 import org.apache.sshd.common.AbstractFactoryManager;
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.Factory;
@@ -230,7 +231,6 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
 
         setupSessionTimeout(sessionFactory);
 
-        sessionFactory.setClient(this);
         connector = createConnector();
     }
 
@@ -276,17 +276,12 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
     }
 
     public ConnectFuture connect(String username, String host, int port) throws IOException {
-        assert host != null;
-        assert port >= 0;
-        if (connector == null) {
-            throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
-        }
-        SocketAddress address = new InetSocketAddress(host, port);
+        ValidateUtils.checkTrue(port >= 0, "Invalid port: %d", port);
+        SocketAddress address = new InetSocketAddress(ValidateUtils.checkNotNullAndNotEmpty(host, "No host"), port);
         return connect(username, address);
     }
 
     public ConnectFuture connect(final String username, SocketAddress address) {
-        assert address != null;
         if (connector == null) {
             throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
         }
@@ -313,7 +308,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
     }
 
     protected SessionFactory createSessionFactory() {
-        return new SessionFactory();
+        return new SessionFactory(this);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/SshKeyScan.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SshKeyScan.java b/sshd-core/src/main/java/org/apache/sshd/client/SshKeyScan.java
index 2a21e75..8e1b49a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SshKeyScan.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SshKeyScan.java
@@ -301,7 +301,7 @@ public class SshKeyScan extends AbstractSimplifiedLog
             }
 
             try {
-                session.addListener(this);
+                session.addSessionListener(this);
                 if (isEnabled(Level.FINER)) {
                     log(Level.FINER, "Authenticating with key type=" + kt + " to " + remoteLocation);
                 }
@@ -324,7 +324,7 @@ public class SshKeyScan extends AbstractSimplifiedLog
                     }
                 }
             } finally {
-                session.removeListener(this);
+                session.removeSessionListener(this);
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
index 1ad6023..8eccb4e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
@@ -32,9 +32,11 @@ import org.apache.sshd.common.channel.AbstractChannel;
 import org.apache.sshd.common.channel.Channel;
 import org.apache.sshd.common.channel.ChannelAsyncInputStream;
 import org.apache.sshd.common.channel.ChannelAsyncOutputStream;
+import org.apache.sshd.common.channel.ChannelListener;
 import org.apache.sshd.common.channel.ChannelRequestHandler;
 import org.apache.sshd.common.io.IoInputStream;
 import org.apache.sshd.common.io.IoOutputStream;
+import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
 import org.apache.sshd.common.util.io.IoUtils;
@@ -250,11 +252,22 @@ public abstract class AbstractClientChannel extends AbstractChannel implements C
     public void handleOpenSuccess(int recipient, int rwSize, int packetSize, Buffer buffer) {
         this.recipient = recipient;
         this.remoteWindow.init(rwSize, packetSize, session.getFactoryManager().getProperties());
+        ChannelListener listener = getChannelListenerProxy();
         try {
             doOpen();
+
+            listener.channelOpenSuccess(this);
             this.opened.set(true);
             this.openFuture.setOpened();
-        } catch (Exception e) {
+        } catch (Throwable t) {
+            Throwable e = GenericUtils.peelException(t);
+            try {
+                listener.channelOpenFailure(this, e);
+            } catch (Throwable ignored) {
+                log.warn("handleOpenSuccess({}) failed ({}) to inform listener of open failure={}: {}",
+                         this, ignored.getClass().getSimpleName(), e.getClass().getSimpleName(), ignored.getMessage());
+            }
+
             this.openFuture.setException(e);
             this.closeFuture.setClosed();
             this.doCloseImmediately();

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/channel/ChannelSession.java
----------------------------------------------------------------------
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 77b2c70..9709f57 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
@@ -171,5 +171,4 @@ public class ChannelSession extends AbstractClientChannel {
             }
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSession.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSession.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSession.java
index 8059eae..b90eade 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSession.java
@@ -340,5 +340,4 @@ public interface ClientSession extends Session {
      */
     @SuppressWarnings("rawtypes")
     SshFuture switchToNoneCipher() throws IOException;
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
index 51f01bb..2b112ea 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
@@ -585,14 +585,14 @@ public class ClientSessionImpl extends AbstractSession implements ClientSession
     }
 
     @Override
-    protected void sendEvent(SessionListener.Event event) throws IOException {
+    protected void sendSessionEvent(SessionListener.Event event) throws IOException {
         if (event == SessionListener.Event.KeyEstablished) {
             sendInitialServiceRequest();
         }
         synchronized (lock) {
             lock.notifyAll();
         }
-        super.sendEvent(event);
+        super.sendSessionEvent(event);
     }
 
     protected void sendInitialServiceRequest() throws IOException {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
index 7ddc0d4..0ef430c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
@@ -220,10 +220,10 @@ public class ClientUserAuthService extends CloseableUtils.AbstractCloseable impl
 
     @Override
     protected void preClose() {
-        super.preClose();
         if (!authFuture.isDone()) {
             authFuture.setException(new SshException("Session is closed"));
         }
-    }
 
+        super.preClose();
+    }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/session/SessionFactory.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/SessionFactory.java b/sshd-core/src/main/java/org/apache/sshd/client/session/SessionFactory.java
new file mode 100644
index 0000000..9e43bed
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/SessionFactory.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session;
+
+import org.apache.sshd.client.ClientFactoryManager;
+import org.apache.sshd.common.io.IoSession;
+import org.apache.sshd.common.session.AbstractSessionFactory;
+
+/**
+ * A factory of client sessions.
+ * This class can be used as a way to customize the creation of client sessions.
+ *
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ * @see org.apache.sshd.client.SshClient#setSessionFactory(SessionFactory)
+ */
+public class SessionFactory extends AbstractSessionFactory<ClientFactoryManager, ClientSessionImpl> {
+
+    public SessionFactory(ClientFactoryManager client) {
+        super(client);
+    }
+
+    public final ClientFactoryManager getClient() {
+        return getFactoryManager();
+    }
+
+    @Override
+    protected ClientSessionImpl doCreateSession(IoSession ioSession) throws Exception {
+        return new ClientSessionImpl(getClient(), ioSession);
+    }
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
index 122c0ab..809b3af 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
@@ -21,6 +21,7 @@ package org.apache.sshd.client.subsystem;
 
 import java.nio.channels.Channel;
 
+import org.apache.sshd.client.channel.ClientChannel;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.NamedResource;
 
@@ -32,4 +33,9 @@ public interface SubsystemClient extends NamedResource, Channel {
      * @return The underlying {@link ClientSession} used
      */
     ClientSession getClientSession();
+
+    /**
+     * @return The underlying {@link ClientChannel} used
+     */
+    ClientChannel getClientChannel();
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/DefaultSftpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/DefaultSftpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/DefaultSftpClient.java
index 5f2c0d4..a4cf4a6 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/DefaultSftpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/DefaultSftpClient.java
@@ -34,6 +34,7 @@ import java.util.TreeMap;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.sshd.client.channel.ChannelSubsystem;
+import org.apache.sshd.client.channel.ClientChannel;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.FactoryManagerUtils;
 import org.apache.sshd.common.SshException;
@@ -107,6 +108,11 @@ public class DefaultSftpClient extends AbstractSftpClient {
     }
 
     @Override
+    public ClientChannel getClientChannel() {
+        return channel;
+    }
+
+    @Override
     public Map<String, byte[]> getServerExtensions() {
         return exposedExtensions;
     }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystem.java b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystem.java
index de91de3..3532e64 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystem.java
@@ -38,6 +38,7 @@ import java.util.Set;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.atomic.AtomicInteger;
 
+import org.apache.sshd.client.channel.ClientChannel;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.FactoryManagerUtils;
 import org.apache.sshd.common.file.util.BaseFileSystem;
@@ -208,6 +209,11 @@ public class SftpFileSystem extends BaseFileSystem<SftpPath> {
         }
 
         @Override
+        public ClientChannel getClientChannel() {
+            return delegate.getClientChannel();
+        }
+
+        @Override
         public Map<String, byte[]> getServerExtensions() {
             return delegate.getServerExtensions();
         }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/AbstractFactoryManager.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/AbstractFactoryManager.java b/sshd-core/src/main/java/org/apache/sshd/common/AbstractFactoryManager.java
index 461149a..962ade1 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/AbstractFactoryManager.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/AbstractFactoryManager.java
@@ -18,15 +18,18 @@
  */
 package org.apache.sshd.common;
 
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.agent.SshAgentFactory;
 import org.apache.sshd.common.channel.Channel;
+import org.apache.sshd.common.channel.ChannelListener;
 import org.apache.sshd.common.channel.RequestHandler;
 import org.apache.sshd.common.cipher.Cipher;
 import org.apache.sshd.common.compression.Compression;
@@ -42,9 +45,11 @@ import org.apache.sshd.common.mac.Mac;
 import org.apache.sshd.common.random.Random;
 import org.apache.sshd.common.session.AbstractSessionFactory;
 import org.apache.sshd.common.session.ConnectionService;
+import org.apache.sshd.common.session.SessionListener;
 import org.apache.sshd.common.session.SessionTimeoutListener;
 import org.apache.sshd.common.signature.Signature;
 import org.apache.sshd.common.util.CloseableUtils;
+import org.apache.sshd.common.util.EventListenerUtils;
 import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.threads.ThreadUtils;
 import org.apache.sshd.server.forward.ForwardingFilter;
@@ -56,7 +61,7 @@ import org.apache.sshd.server.forward.ForwardingFilter;
  */
 public abstract class AbstractFactoryManager extends CloseableUtils.AbstractInnerCloseable implements FactoryManager {
 
-    protected Map<String, Object> properties = new HashMap<String, Object>();
+    protected Map<String, Object> properties = new HashMap<>();
     protected IoServiceFactoryFactory ioServiceFactoryFactory;
     protected IoServiceFactory ioServiceFactory;
     protected List<NamedFactory<KeyExchange>> keyExchangeFactories;
@@ -77,9 +82,15 @@ public abstract class AbstractFactoryManager extends CloseableUtils.AbstractInne
     protected List<RequestHandler<ConnectionService>> globalRequestHandlers;
     protected SessionTimeoutListener sessionTimeoutListener;
     protected ScheduledFuture<?> timeoutListenerFuture;
+    protected final Collection<SessionListener> sessionListeners = new CopyOnWriteArraySet<>();
+    protected final SessionListener sessionListenerProxy;
+    protected final Collection<ChannelListener> channelListeners = new CopyOnWriteArraySet<>();
+    protected final ChannelListener channelListenerProxy;
 
     protected AbstractFactoryManager() {
-        super();
+        ClassLoader loader = getClass().getClassLoader();
+        sessionListenerProxy = EventListenerUtils.proxyWrapper(SessionListener.class, loader, sessionListeners);
+        channelListenerProxy = EventListenerUtils.proxyWrapper(ChannelListener.class, loader, channelListeners);
     }
 
     @Override
@@ -271,16 +282,76 @@ public abstract class AbstractFactoryManager extends CloseableUtils.AbstractInne
         this.globalRequestHandlers = globalRequestHandlers;
     }
 
-    protected void setupSessionTimeout(final AbstractSessionFactory sessionFactory) {
+    @Override
+    public void addSessionListener(SessionListener listener) {
+        ValidateUtils.checkNotNull(listener, "addSessionListener(%s) null instance", this);
+        // avoid race conditions on notifications while manager is being closed
+        if (!isOpen()) {
+            log.warn("addSessionListener({})[{}] ignore registration while manager is closing", this, listener);
+            return;
+        }
+
+        if (this.sessionListeners.add(listener)) {
+            log.trace("addSessionListener({})[{}] registered", this, listener);
+        } else {
+            log.trace("addSessionListener({})[{}] ignored duplicate", this, listener);
+        }
+    }
+
+    @Override
+    public void removeSessionListener(SessionListener listener) {
+        if (this.sessionListeners.remove(listener)) {
+            log.trace("removeSessionListener({})[{}] removed", this, listener);
+        } else {
+            log.trace("removeSessionListener({})[{}] not registered", this, listener);
+        }
+    }
+
+    @Override
+    public SessionListener getSessionListenerProxy() {
+        return sessionListenerProxy;
+    }
+
+    @Override
+    public void addChannelListener(ChannelListener listener) {
+        ValidateUtils.checkNotNull(listener, "addChannelListener(%s) null instance", this);
+        // avoid race conditions on notifications while manager is being closed
+        if (!isOpen()) {
+            log.warn("addChannelListener({})[{}] ignore registration while session is closing", this, listener);
+            return;
+        }
+
+        if (this.channelListeners.add(listener)) {
+            log.trace("addChannelListener({})[{}] registered", this, listener);
+        } else {
+            log.trace("addChannelListener({})[{}] ignored duplicate", this, listener);
+        }
+    }
+
+    @Override
+    public void removeChannelListener(ChannelListener listener) {
+        if (this.channelListeners.remove(listener)) {
+            log.trace("removeChannelListener({})[{}] removed", this, listener);
+        } else {
+            log.trace("removeChannelListener({})[{}] not registered", this, listener);
+        }
+    }
+
+    @Override
+    public ChannelListener getChannelListenerProxy() {
+        return channelListenerProxy;
+    }
+
+    protected void setupSessionTimeout(final AbstractSessionFactory<?, ?> sessionFactory) {
         // set up the the session timeout listener and schedule it
         sessionTimeoutListener = createSessionTimeoutListener();
-        sessionFactory.addListener(sessionTimeoutListener);
+        addSessionListener(sessionTimeoutListener);
 
         timeoutListenerFuture = getScheduledExecutorService()
                 .scheduleAtFixedRate(sessionTimeoutListener, 1, 1, TimeUnit.SECONDS);
     }
 
-    protected void removeSessionTimeout(final AbstractSessionFactory sessionFactory) {
+    protected void removeSessionTimeout(final AbstractSessionFactory<?, ?> sessionFactory) {
         stopSessionTimeoutListener(sessionFactory);
     }
 
@@ -288,19 +359,25 @@ public abstract class AbstractFactoryManager extends CloseableUtils.AbstractInne
         return new SessionTimeoutListener();
     }
 
-    protected void stopSessionTimeoutListener(final AbstractSessionFactory sessionFactory) {
+    protected void stopSessionTimeoutListener(final AbstractSessionFactory<?, ?> sessionFactory) {
         // cancel the timeout monitoring task
         if (timeoutListenerFuture != null) {
-            timeoutListenerFuture.cancel(true);
-            timeoutListenerFuture = null;
+            try {
+                timeoutListenerFuture.cancel(true);
+            } finally {
+                timeoutListenerFuture = null;
+            }
         }
 
         // remove the sessionTimeoutListener completely; should the SSH server/client be restarted, a new one
         // will be created.
-        if (sessionFactory != null && sessionTimeoutListener != null) {
-            sessionFactory.removeListener(sessionTimeoutListener);
+        if (sessionTimeoutListener != null) {
+            try {
+                removeSessionListener(sessionTimeoutListener);
+            } finally {
+                sessionTimeoutListener = null;
+            }
         }
-        sessionTimeoutListener = null;
     }
 
     protected void checkConfig() {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/FactoryManager.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/FactoryManager.java b/sshd-core/src/main/java/org/apache/sshd/common/FactoryManager.java
index 734fb6a..ee8f168 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/FactoryManager.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/FactoryManager.java
@@ -24,6 +24,7 @@ import java.util.concurrent.ScheduledExecutorService;
 
 import org.apache.sshd.agent.SshAgentFactory;
 import org.apache.sshd.common.channel.Channel;
+import org.apache.sshd.common.channel.ChannelListenerManager;
 import org.apache.sshd.common.channel.RequestHandler;
 import org.apache.sshd.common.cipher.Cipher;
 import org.apache.sshd.common.compression.Compression;
@@ -35,6 +36,7 @@ import org.apache.sshd.common.keyprovider.KeyPairProvider;
 import org.apache.sshd.common.mac.Mac;
 import org.apache.sshd.common.random.Random;
 import org.apache.sshd.common.session.ConnectionService;
+import org.apache.sshd.common.session.SessionListenerManager;
 import org.apache.sshd.common.signature.Signature;
 import org.apache.sshd.server.forward.ForwardingFilter;
 
@@ -44,7 +46,7 @@ import org.apache.sshd.server.forward.ForwardingFilter;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface FactoryManager {
+public interface FactoryManager extends SessionListenerManager, ChannelListenerManager {
 
     /**
      * Key used to retrieve the value of the window size in the

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/channel/AbstractChannel.java
----------------------------------------------------------------------
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 e468da4..04ed9ad 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
@@ -22,6 +22,7 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
+import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -38,8 +39,10 @@ import org.apache.sshd.common.io.IoWriteFuture;
 import org.apache.sshd.common.session.ConnectionService;
 import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.util.CloseableUtils;
+import org.apache.sshd.common.util.EventListenerUtils;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.Int2IntFunction;
+import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.buffer.BufferUtils;
 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
@@ -80,6 +83,11 @@ public abstract class AbstractChannel
     protected AtomicReference<GracefulState> gracefulState = new AtomicReference<GracefulState>(GracefulState.Opened);
     protected final DefaultCloseFuture gracefulFuture = new DefaultCloseFuture(lock);
     protected final List<RequestHandler<Channel>> handlers = new ArrayList<RequestHandler<Channel>>();
+    /**
+     * Channel events listener
+     */
+    protected final Collection<ChannelListener> channelListeners = new CopyOnWriteArraySet<>();
+    protected final ChannelListener channelListenerProxy;
 
     protected AbstractChannel() {
         this("");
@@ -87,6 +95,7 @@ public abstract class AbstractChannel
 
     protected AbstractChannel(String discriminator) {
         super(discriminator);
+        channelListenerProxy = EventListenerUtils.proxyWrapper(ChannelListener.class, getClass().getClassLoader(), channelListeners);
     }
 
     public void addRequestHandler(RequestHandler<Channel> handler) {
@@ -195,10 +204,20 @@ public abstract class AbstractChannel
     }
 
     @Override
-    public void init(ConnectionService service, Session session, int id) {
+    public void init(ConnectionService service, Session session, int id) throws IOException {
         this.service = service;
         this.session = session;
         this.id = id;
+
+        ChannelListener listener = session.getChannelListenerProxy();
+        try {
+            listener.channelInitialized(this);
+        } catch (RuntimeException t) {
+            Throwable e = GenericUtils.peelException(t);
+            throw new IOException("Failed (" + e.getClass().getSimpleName() + ") to notify channel " + toString() + " initialization: " + e.getMessage(), e);
+        }
+        // delegate the rest of the notifications to the channel
+        addChannelListener(listener);
         configureWindow();
     }
 
@@ -209,6 +228,36 @@ public abstract class AbstractChannel
     }
 
     @Override
+    public void addChannelListener(ChannelListener listener) {
+        ValidateUtils.checkNotNull(listener, "addChannelListener(%s) null instance", this);
+        // avoid race conditions on notifications while channel is being closed
+        if (!isOpen()) {
+            log.warn("addChannelListener({})[{}] ignore registration while channel is closing", this, listener);
+            return;
+        }
+
+        if (this.channelListeners.add(listener)) {
+            log.trace("addChannelListener({})[{}] registered", this, listener);
+        } else {
+            log.trace("addChannelListener({})[{}] ignored duplicate", this, listener);
+        }
+    }
+
+    @Override
+    public void removeChannelListener(ChannelListener listener) {
+        if (this.channelListeners.remove(listener)) {
+            log.trace("removeChannelListener({})[{}] removed", this, listener);
+        } else {
+            log.trace("removeChannelListener({})[{}] not registered", this, listener);
+        }
+    }
+
+    @Override
+    public ChannelListener getChannelListenerProxy() {
+        return channelListenerProxy;
+    }
+
+    @Override
     public void handleClose() throws IOException {
         log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", this);
         if (gracefulState.compareAndSet(GracefulState.Opened, GracefulState.CloseReceived)) {
@@ -252,8 +301,9 @@ public abstract class AbstractChannel
                 gracefulFuture.setClosed();
             } else if (!gracefulFuture.isClosed()) {
                 log.debug("Send SSH_MSG_CHANNEL_CLOSE on channel {}", AbstractChannel.this);
-                Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_CLOSE);
-                buffer.putInt(recipient);
+                Session s = getSession();
+                Buffer buffer = s.createBuffer(SshConstants.SSH_MSG_CHANNEL_CLOSE);
+                buffer.putInt(getRecipient());
                 try {
                     long timeout = FactoryManagerUtils.getLongProperty(getSession(), FactoryManager.CHANNEL_CLOSE_TIMEOUT, DEFAULT_CHANNEL_CLOSE_TIMEOUT);
                     session.writePacket(buffer, timeout, TimeUnit.MILLISECONDS).addListener(new SshFutureListener<IoWriteFuture>() {
@@ -292,6 +342,20 @@ public abstract class AbstractChannel
     }
 
     @Override
+    protected void preClose() {
+        ChannelListener listener = getChannelListenerProxy();
+        try {
+            listener.channelClosed(this);
+        } catch (RuntimeException t) {
+            Throwable e = GenericUtils.peelException(t);
+            log.warn(e.getClass().getSimpleName() + " while signal channel " + toString() + " closed: " + e.getMessage(), e);
+        } finally {
+            // clear the listeners since we are closing the channel (quicker GC)
+            this.channelListeners.clear();
+        }
+    }
+
+    @Override
     protected void doCloseImmediately() {
         if (service != null) {
             service.unregisterChannel(AbstractChannel.this);
@@ -301,9 +365,10 @@ public abstract class AbstractChannel
 
     protected void writePacket(Buffer buffer) throws IOException {
         if (!isClosing()) {
-            session.writePacket(buffer);
+            Session s = getSession();
+            s.writePacket(buffer);
         } else {
-            log.debug("Discarding output packet because channel is being closed");
+            log.debug("writePacket({}) Discarding output packet because channel is being closed", this);
         }
     }
 
@@ -326,8 +391,9 @@ public abstract class AbstractChannel
         // Only accept extended data for stderr
         if (ex != 1) {
             log.debug("Send SSH_MSG_CHANNEL_FAILURE on channel {}", this);
-            buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_FAILURE);
-            buffer.putInt(recipient);
+            Session s = getSession();
+            buffer = s.createBuffer(SshConstants.SSH_MSG_CHANNEL_FAILURE);
+            buffer.putInt(getRecipient());
             writePacket(buffer);
             return;
         }
@@ -376,27 +442,29 @@ public abstract class AbstractChannel
 
     protected void sendEof() throws IOException {
         log.debug("Send SSH_MSG_CHANNEL_EOF on channel {}", this);
-        Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_EOF);
-        buffer.putInt(recipient);
+        Session s = getSession();
+        Buffer buffer = s.createBuffer(SshConstants.SSH_MSG_CHANNEL_EOF);
+        buffer.putInt(getRecipient());
         writePacket(buffer);
     }
 
     protected void configureWindow() {
-        localWindow.init(session);
+        localWindow.init(getSession());
     }
 
     protected void sendWindowAdjust(int len) throws IOException {
         if (log.isDebugEnabled()) {
             log.debug("Send SSH_MSG_CHANNEL_WINDOW_ADJUST on channel {}", Integer.valueOf(id));
         }
-        Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_WINDOW_ADJUST);
-        buffer.putInt(recipient);
+        Session s = getSession();
+        Buffer buffer = s.createBuffer(SshConstants.SSH_MSG_CHANNEL_WINDOW_ADJUST);
+        buffer.putInt(getRecipient());
         buffer.putInt(len);
         writePacket(buffer);
     }
 
     @Override
     public String toString() {
-        return getClass().getSimpleName() + "[id=" + id + ", recipient=" + recipient + "]";
+        return getClass().getSimpleName() + "[id=" + getId() + ", recipient=" + getRecipient() + "]";
     }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
index 1d55d8a..e4b0635 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
@@ -28,11 +28,12 @@ import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.util.buffer.Buffer;
 
 /**
- * TODO Add javadoc
+ * Represents a channel opened over an SSH session - holds information that is
+ * common both to server and client channels.
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface Channel extends Closeable {
+public interface Channel extends ChannelListenerManager, Closeable {
 
     /**
      * @return Local channel identifier
@@ -109,5 +110,4 @@ public interface Channel extends Closeable {
      * @throws IOException If failed to handle the success
      */
     void handleOpenFailure(Buffer buffer) throws IOException;
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncInputStream.java
----------------------------------------------------------------------
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 b1798be..eaef733 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
@@ -33,6 +33,9 @@ import org.apache.sshd.common.util.Readable;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
 
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
 public class ChannelAsyncInputStream extends CloseableUtils.AbstractCloseable implements IoInputStream {
 
     private final Channel channel;
@@ -76,6 +79,7 @@ public class ChannelAsyncInputStream extends CloseableUtils.AbstractCloseable im
                 }
             }
         }
+        super.preClose();
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListener.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListener.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListener.java
new file mode 100644
index 0000000..4a4078c
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListener.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.common.channel;
+
+import java.util.EventListener;
+
+/**
+ * Provides a simple listener for client / server channels being established
+ * or torn down. <B>Note:</B> for server-side listeners, some of the established
+ * channels may be <U>client</U> - especially where connection proxy or forwarding
+ * is concerned
+ *
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public interface ChannelListener extends EventListener {
+    /**
+     * Called to inform about initial setup of a channel via the
+     * {@link Channel#init(org.apache.sshd.common.session.ConnectionService, org.apache.sshd.common.session.Session, int)}
+     * method. <B>Note:</B> this method is guaranteed to be called
+     * before either of the {@link #channelOpenSuccess(Channel)} or
+     * {@link #channelOpenFailure(Channel, Throwable)} will be called
+     *
+     * @param channel The initialized {@link Channel}
+     */
+    void channelInitialized(Channel channel);
+
+    /**
+     * Called to inform about a channel being successfully opened for a
+     * session. <B>Note:</B> when the call is made, the channel is known
+     * to be open but nothing beyond that.
+     *
+     * @param channel The newly opened {@link Channel}
+     */
+    void channelOpenSuccess(Channel channel);
+
+    /**
+     * Called to inform about the failure to open a channel
+     *
+     * @param channel The failed {@link Channel}
+     * @param reason The {@link Throwable} reason - <B>Note:</B> if the
+     * {@link #channelOpenSuccess(Channel)} notification throws an exception
+     * it will cause this method to be invoked
+     */
+    void channelOpenFailure(Channel channel, Throwable reason);
+
+    /**
+     * Called to inform about a channel being closed. <B>Note:</B> when the call
+     * is made there are no guarantees about the channel's actual state
+     * except that it either has been already closed or may be in the process
+     * of being closed. <B>Note:</B> this method is guaranteed to be called
+     * regardless of whether {@link #channelOpenSuccess(Channel)} or
+     * {@link #channelOpenFailure(Channel, Throwable)} have been called
+     *
+     * @param channel The referenced {@link Channel}
+     */
+    void channelClosed(Channel channel);
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListenerManager.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListenerManager.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListenerManager.java
new file mode 100644
index 0000000..511379b
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelListenerManager.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.common.channel;
+
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public interface ChannelListenerManager {
+    /**
+     * Add a channel listener
+     *
+     * @param listener The {@link ChannelListener} to add - not {@code null}
+     */
+    void addChannelListener(ChannelListener listener);
+
+    /**
+     * Remove a channel listener
+     *
+     * @param listener The {@link ChannelListener} to remove
+     */
+    void removeChannelListener(ChannelListener listener);
+
+    /**
+     * @return A (never {@code null} proxy {@link ChannelListener} that represents
+     * all the currently registered listeners. Any method invocation on the proxy
+     * is replicated to the currently registered listeners
+     */
+    ChannelListener getChannelListenerProxy();
+
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelPipedInputStream.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelPipedInputStream.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelPipedInputStream.java
index a904bc2..3df0526 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelPipedInputStream.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelPipedInputStream.java
@@ -23,6 +23,7 @@ import java.io.InputStream;
 import java.io.InterruptedIOException;
 import java.net.SocketException;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
@@ -44,20 +45,20 @@ public class ChannelPipedInputStream extends InputStream implements ChannelPiped
     private final Window localWindow;
     private final Buffer buffer = new ByteArrayBuffer();
     private final byte[] b = new byte[1];
-    private boolean closed;
-    private boolean eofSent;
+    private final AtomicBoolean closed = new AtomicBoolean(false);
+    private final AtomicBoolean eofSent = new AtomicBoolean(false);
 
     private final Lock lock = new ReentrantLock();
     private final Condition dataAvailable = lock.newCondition();
 
-    private long timeout;
-
     /**
      * {@link ChannelPipedOutputStream} is already closed and so we will not receive additional data.
      * This is different from the {@link #closed}, which indicates that the reader of this {@link InputStream}
      * will not be reading data any more.
      */
-    private boolean writerClosed;
+    private final AtomicBoolean writerClosed = new AtomicBoolean(false);
+
+    private long timeout;
 
     public ChannelPipedInputStream(Window localWindow) {
         this.localWindow = ValidateUtils.checkNotNull(localWindow, "No local window provided");
@@ -77,7 +78,7 @@ public class ChannelPipedInputStream extends InputStream implements ChannelPiped
         lock.lock();
         try {
             int avail = buffer.available();
-            if (avail == 0 && writerClosed) {
+            if ((avail == 0) && writerClosed.get()) {
                 return -1;
             }
             return avail;
@@ -103,14 +104,14 @@ public class ChannelPipedInputStream extends InputStream implements ChannelPiped
         lock.lock();
         try {
             for (int index = 0;; index++) {
-                if ((closed && writerClosed && eofSent) || (closed && !writerClosed)) {
+                if ((closed.get() && writerClosed.get() && eofSent.get()) || (closed.get() && (!writerClosed.get()))) {
                     throw new IOException("Pipe closed after " + index + " cycles");
                 }
                 if (buffer.available() > 0) {
                     break;
                 }
-                if (writerClosed) {
-                    eofSent = true;
+                if (writerClosed.get()) {
+                    eofSent.set(true);
                     return -1; // no more data to read
                 }
 
@@ -146,7 +147,7 @@ public class ChannelPipedInputStream extends InputStream implements ChannelPiped
     public void eof() {
         lock.lock();
         try {
-            writerClosed = true;
+            writerClosed.set(true);
             dataAvailable.signalAll();
         } finally {
             lock.unlock();
@@ -159,7 +160,7 @@ public class ChannelPipedInputStream extends InputStream implements ChannelPiped
         try {
             dataAvailable.signalAll();
         } finally {
-            closed = true;
+            closed.set(true);
             lock.unlock();
         }
     }
@@ -168,7 +169,7 @@ public class ChannelPipedInputStream extends InputStream implements ChannelPiped
     public void receive(byte[] bytes, int off, int len) throws IOException {
         lock.lock();
         try {
-            if (writerClosed || closed) {
+            if (writerClosed.get() || closed.get()) {
                 throw new IOException("Pipe closed");
             }
             buffer.putRawBytes(bytes, off, len);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultSshFuture.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultSshFuture.java b/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultSshFuture.java
index 2b911e1..92c915c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultSshFuture.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/future/DefaultSshFuture.java
@@ -150,10 +150,19 @@ public class DefaultSshFuture<T extends SshFuture> extends AbstractLoggingBean i
         Class<?> actualType = value.getClass();
         if (expectedType.isAssignableFrom(actualType)) {
             return expectedType.cast(value);
-        } else if (IOException.class.isAssignableFrom(actualType)) {
-            throw (IOException) value;
-        } else if (Throwable.class.isAssignableFrom(actualType)) {
-            Throwable t = (Throwable) value;
+        }
+
+        if (Throwable.class.isAssignableFrom(actualType)) {
+            Throwable t = GenericUtils.peelException((Throwable) value);
+            if (t != value) {
+                value = t;
+                actualType = value.getClass();
+            }
+
+            if (IOException.class.isAssignableFrom(actualType)) {
+                throw (IOException) value;
+            }
+
             throw new SshException("Failed (" + t.getClass().getSimpleName() + ") to execute: " + t.getMessage(), GenericUtils.resolveExceptionCause(t));
         } else {    // what else can it be ????
             throw new StreamCorruptedException("Unknown result type: " + actualType.getName());

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
index 9ccc2da..8b1b59d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
@@ -21,13 +21,13 @@ package org.apache.sshd.common.session;
 import java.io.IOException;
 import java.io.InterruptedIOException;
 import java.nio.charset.StandardCharsets;
+import java.util.Collection;
 import java.util.EnumMap;
 import java.util.LinkedList;
-import java.util.List;
 import java.util.Map;
 import java.util.Queue;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
@@ -43,6 +43,7 @@ import org.apache.sshd.common.NamedResource;
 import org.apache.sshd.common.Service;
 import org.apache.sshd.common.SshConstants;
 import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.channel.ChannelListener;
 import org.apache.sshd.common.cipher.Cipher;
 import org.apache.sshd.common.compression.Compression;
 import org.apache.sshd.common.digest.Digest;
@@ -65,21 +66,12 @@ import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.buffer.BufferUtils;
 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
 
-import static org.apache.sshd.common.SshConstants.SSH_MSG_DEBUG;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_DISCONNECT;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_IGNORE;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_KEXINIT;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_NEWKEYS;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_SERVICE_ACCEPT;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_SERVICE_REQUEST;
-import static org.apache.sshd.common.SshConstants.SSH_MSG_UNIMPLEMENTED;
-
 /**
  * <P>
  * The AbstractSession handles all the basic SSH protocol such as key exchange, authentication,
  * encoding and decoding. Both server side and client side sessions should inherit from this
  * abstract class. Some basic packet processing methods are defined but the actual call to these
- * methods should be done from the {@link #handleMessage(org.apache.sshd.common.util.buffer.Buffer)}
+ * methods should be done from the {@link #handleMessage(Buffer)}
  * method, which is dependent on the state and side of this session.
  * </P>
  *
@@ -128,8 +120,15 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     /**
      * Session listeners container
      */
-    protected final List<SessionListener> listeners = new CopyOnWriteArrayList<SessionListener>();
+    protected final Collection<SessionListener> sessionListeners = new CopyOnWriteArraySet<>();
     protected final SessionListener sessionListenerProxy;
+
+    /**
+     * Channel events listener
+     */
+    protected final Collection<ChannelListener> channelListeners = new CopyOnWriteArraySet<>();
+    protected final ChannelListener channelListenerProxy;
+
     //
     // Key exchange support
     //
@@ -202,7 +201,11 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
         this.isServer = isServer;
         this.factoryManager = ValidateUtils.checkNotNull(factoryManager, "No factory manager provided", GenericUtils.EMPTY_OBJECT_ARRAY);
         this.ioSession = ioSession;
-        sessionListenerProxy = EventListenerUtils.proxyWrapper(SessionListener.class, getClass().getClassLoader(), listeners);
+
+        ClassLoader loader = getClass().getClassLoader();
+        sessionListenerProxy = EventListenerUtils.proxyWrapper(SessionListener.class, loader, sessionListeners);
+        channelListenerProxy = EventListenerUtils.proxyWrapper(ChannelListener.class, loader, channelListeners);
+
         random = factoryManager.getRandomFactory().create();
         authTimeoutMs = getLongProperty(FactoryManager.AUTH_TIMEOUT, authTimeoutMs);
         authTimeoutTimestamp = System.currentTimeMillis() + authTimeoutMs;
@@ -301,7 +304,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     @Override
     public void setAuthenticated() throws IOException {
         this.authed = true;
-        sendEvent(SessionListener.Event.Authenticated);
+        sendSessionEvent(SessionListener.Event.Authenticated);
     }
 
     /**
@@ -353,22 +356,22 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     protected void doHandleMessage(Buffer buffer) throws Exception {
         int cmd = buffer.getUByte();
         switch (cmd) {
-            case SSH_MSG_DISCONNECT: {
+            case SshConstants.SSH_MSG_DISCONNECT: {
                 handleDisconnect(buffer);
                 break;
             }
-            case SSH_MSG_IGNORE: {
+            case SshConstants.SSH_MSG_IGNORE: {
                 log.debug("Received SSH_MSG_IGNORE");
                 break;
             }
-            case SSH_MSG_UNIMPLEMENTED: {
+            case SshConstants.SSH_MSG_UNIMPLEMENTED: {
                 int code = buffer.getInt();
                 if (log.isDebugEnabled()) {
                     log.debug("Received SSH_MSG_UNIMPLEMENTED #{}", Integer.valueOf(code));
                 }
                 break;
             }
-            case SSH_MSG_DEBUG: {
+            case SshConstants.SSH_MSG_DEBUG: {
                 boolean display = buffer.getBoolean();
                 String msg = buffer.getString();
                 if (log.isDebugEnabled()) {
@@ -376,16 +379,16 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
                 }
                 break;
             }
-            case SSH_MSG_SERVICE_REQUEST:
+            case SshConstants.SSH_MSG_SERVICE_REQUEST:
                 handleServiceRequest(buffer);
                 break;
-            case SSH_MSG_SERVICE_ACCEPT:
+            case SshConstants.SSH_MSG_SERVICE_ACCEPT:
                 handleServiceAccept();
                 break;
-            case SSH_MSG_KEXINIT:
+            case SshConstants.SSH_MSG_KEXINIT:
                 handleKexInit(buffer);
                 break;
-            case SSH_MSG_NEWKEYS:
+            case SshConstants.SSH_MSG_NEWKEYS:
                 handleNewKeys(cmd);
                 break;
             default:
@@ -420,7 +423,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     private void handleServiceRequest(Buffer buffer) throws IOException {
         String service = buffer.getString();
         log.debug("Received SSH_MSG_SERVICE_REQUEST '{}'", service);
-        validateKexState(SSH_MSG_SERVICE_REQUEST, KexState.DONE);
+        validateKexState(SshConstants.SSH_MSG_SERVICE_REQUEST, KexState.DONE);
         try {
             startService(service);
         } catch (Exception e) {
@@ -434,39 +437,39 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
         writePacket(response);
     }
 
-    private void handleServiceAccept() throws java.io.IOException {
+    private void handleServiceAccept() throws IOException {
         log.debug("Received SSH_MSG_SERVICE_ACCEPT");
-        validateKexState(SSH_MSG_SERVICE_ACCEPT, org.apache.sshd.common.kex.KexState.DONE);
+        validateKexState(SshConstants.SSH_MSG_SERVICE_ACCEPT, KexState.DONE);
         serviceAccept();
     }
 
-    private void handleKexInit(org.apache.sshd.common.util.buffer.Buffer buffer) throws Exception {
+    private void handleKexInit(Buffer buffer) throws Exception {
         log.debug("Received SSH_MSG_KEXINIT");
         receiveKexInit(buffer);
-        if (kexState.compareAndSet(org.apache.sshd.common.kex.KexState.DONE, org.apache.sshd.common.kex.KexState.RUN)) {
+        if (kexState.compareAndSet(KexState.DONE, KexState.RUN)) {
             sendKexInit();
-        } else if (!kexState.compareAndSet(org.apache.sshd.common.kex.KexState.INIT, org.apache.sshd.common.kex.KexState.RUN)) {
+        } else if (!kexState.compareAndSet(KexState.INIT, KexState.RUN)) {
             throw new IllegalStateException("Received SSH_MSG_KEXINIT while key exchange is running");
         }
 
-        java.util.Map<org.apache.sshd.common.kex.KexProposalOption, String> result = negotiate();
-        String kexAlgorithm = result.get(org.apache.sshd.common.kex.KexProposalOption.ALGORITHMS);
-        kex = org.apache.sshd.common.util.ValidateUtils.checkNotNull(org.apache.sshd.common.NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), kexAlgorithm),
+        Map<KexProposalOption, String> result = negotiate();
+        String kexAlgorithm = result.get(KexProposalOption.ALGORITHMS);
+        kex = ValidateUtils.checkNotNull(NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), kexAlgorithm),
                 "Unknown negotiated KEX algorithm: %s",
                 kexAlgorithm);
-        kex.init(this, serverVersion.getBytes(java.nio.charset.StandardCharsets.UTF_8), clientVersion.getBytes(java.nio.charset.StandardCharsets.UTF_8), i_s, i_c);
+        kex.init(this, serverVersion.getBytes(StandardCharsets.UTF_8), clientVersion.getBytes(StandardCharsets.UTF_8), i_s, i_c);
 
-        sendEvent(org.apache.sshd.common.session.SessionListener.Event.KexCompleted);
+        sendSessionEvent(SessionListener.Event.KexCompleted);
     }
 
     private void handleNewKeys(int cmd) throws Exception {
         log.debug("Received SSH_MSG_NEWKEYS");
-        validateKexState(cmd, org.apache.sshd.common.kex.KexState.KEYS);
+        validateKexState(cmd, KexState.KEYS);
         receiveNewKeys();
         if (reexchangeFuture != null) {
             reexchangeFuture.setValue(Boolean.TRUE);
         }
-        sendEvent(org.apache.sshd.common.session.SessionListener.Event.KeyEstablished);
+        sendSessionEvent(SessionListener.Event.KeyEstablished);
         synchronized (pendingPackets) {
             if (!pendingPackets.isEmpty()) {
                 log.debug("Dequeing pending packets");
@@ -477,7 +480,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
                     }
                 }
             }
-            kexState.set(org.apache.sshd.common.kex.KexState.DONE);
+            kexState.set(KexState.DONE);
         }
         synchronized (lock) {
             lock.notifyAll();
@@ -495,7 +498,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
      * Handle any exceptions that occurred on this session.
      * The session will be closed and a disconnect packet will be
      * sent before if the given exception is an
-     * {@link org.apache.sshd.common.SshException}.
+     * {@link SshException}.
      *
      * @param t the exception to process
      */
@@ -534,10 +537,19 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     }
 
     @Override
-    protected void doCloseImmediately() {
-        super.doCloseImmediately();
+    protected void preClose() {
         // Fire 'close' event
-        sessionListenerProxy.sessionClosed(this);
+        SessionListener listener = getSessionListenerProxy();
+        try {
+            listener.sessionClosed(this);
+        } catch (RuntimeException t) {
+            Throwable e = GenericUtils.peelException(t);
+            log.warn(e.getClass().getSimpleName() + " while signal session " + toString() + " closed: " + e.getMessage(), e);
+        } finally {
+            // clear the listeners since we are closing the session (quicker GC)
+            this.sessionListeners.clear();
+            this.channelListeners.clear();
+        }
     }
 
     protected Service[] getServices() {
@@ -561,7 +573,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
      *
      * @param buffer the buffer to encode and send
      * @return a future that can be used to check when the packet has actually been sent
-     * @throws java.io.IOException if an error occured when encoding sending the packet
+     * @throws IOException if an error occurred when encoding sending the packet
      */
     @Override
     public IoWriteFuture writePacket(Buffer buffer) throws IOException {
@@ -630,7 +642,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
      *
      * @param buffer the buffer containing the global request
      * @return <code>true</code> if the request was successful, <code>false</code> otherwise.
-     * @throws java.io.IOException if an error occured when encoding sending the packet
+     * @throws IOException if an error occurred when encoding sending the packet
      */
     @Override
     public Buffer request(Buffer buffer) throws IOException {
@@ -873,7 +885,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     /**
      * Read the other side identification.
      * This method is specific to the client or server side, but both should call
-     * {@link #doReadIdentification(org.apache.sshd.common.util.buffer.Buffer, boolean)} and
+     * {@link #doReadIdentification(Buffer, boolean)} and
      * store the result in the needed property.
      *
      * @param buffer the buffer containing the remote identification
@@ -1397,18 +1409,68 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     }
 
     @Override
-    public void addListener(SessionListener listener) {
-        ValidateUtils.checkNotNull(listener, "addListener(%s) null instance", this);
-        this.listeners.add(listener);
+    public void addSessionListener(SessionListener listener) {
+        ValidateUtils.checkNotNull(listener, "addSessionListener(%s) null instance", this);
+        // avoid race conditions on notifications while session is being closed
+        if (!isOpen()) {
+            log.warn("addSessionListener({})[{}] ignore registration while session is closing", this, listener);
+            return;
+        }
+
+        if (this.sessionListeners.add(listener)) {
+            log.trace("addSessionListener({})[{}] registered", this, listener);
+        } else {
+            log.trace("addSessionListener({})[{}] ignored duplicate", this, listener);
+        }
+    }
+
+    @Override
+    public void removeSessionListener(SessionListener listener) {
+        if (this.sessionListeners.remove(listener)) {
+            log.trace("removeSessionListener({})[{}] removed", this, listener);
+        } else {
+            log.trace("removeSessionListener({})[{}] not registered", this, listener);
+        }
+    }
+
+    @Override
+    public SessionListener getSessionListenerProxy() {
+        return sessionListenerProxy;
+    }
+
+    @Override
+    public void addChannelListener(ChannelListener listener) {
+        ValidateUtils.checkNotNull(listener, "addChannelListener(%s) null instance", this);
+        // avoid race conditions on notifications while session is being closed
+        if (!isOpen()) {
+            log.warn("addChannelListener({})[{}] ignore registration while session is closing", this, listener);
+            return;
+        }
+
+        if (this.channelListeners.add(listener)) {
+            log.trace("addChannelListener({})[{}] registered", this, listener);
+        } else {
+            log.trace("addChannelListener({})[{}] ignored duplicate", this, listener);
+        }
+    }
+
+    @Override
+    public void removeChannelListener(ChannelListener listener) {
+        if (this.channelListeners.remove(listener)) {
+            log.trace("removeChannelListener({})[{}] removed", this, listener);
+        } else {
+            log.trace("removeChannelListener({})[{}] not registered", this, listener);
+        }
     }
 
     @Override
-    public void removeListener(SessionListener listener) {
-        this.listeners.remove(listener);
+    public ChannelListener getChannelListenerProxy() {
+        return channelListenerProxy;
     }
 
-    protected void sendEvent(SessionListener.Event event) throws IOException {
-        sessionListenerProxy.sessionEvent(this, event);
+    protected void sendSessionEvent(SessionListener.Event event) throws IOException {
+        SessionListener listener = getSessionListenerProxy();
+        listener.sessionEvent(this, event);
     }
 
     @Override
@@ -1509,11 +1571,11 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
     protected void checkForTimeouts() throws IOException {
         if (!isClosing()) {
             long now = System.currentTimeMillis();
-            if (!authed && authTimeoutMs > 0 && now > authTimeoutTimestamp) {
+            if ((!authed) && (authTimeoutMs > 0L) && (now > authTimeoutTimestamp)) {
                 timeoutStatus.set(TimeoutStatus.AuthTimeout);
                 disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Session has timed out waiting for authentication after " + authTimeoutMs + " ms.");
             }
-            if (idleTimeoutMs > 0 && idleTimeoutTimestamp > 0 && now > idleTimeoutTimestamp) {
+            if ((idleTimeoutMs > 0) && (idleTimeoutTimestamp > 0L) && (now > idleTimeoutTimestamp)) {
                 timeoutStatus.set(TimeoutStatus.AuthTimeout);
                 disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "User session has timed out idling after " + idleTimeoutMs + " ms.");
             }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
index eb8636b..37fa761 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
@@ -18,9 +18,7 @@
  */
 package org.apache.sshd.common.session;
 
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
+import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.common.io.IoSession;
 import org.apache.sshd.common.util.ValidateUtils;
 
@@ -29,45 +27,32 @@ import org.apache.sshd.common.util.ValidateUtils;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public abstract class AbstractSessionFactory extends AbstractSessionIoHandler {
+public abstract class AbstractSessionFactory<M extends FactoryManager, S extends AbstractSession> extends AbstractSessionIoHandler {
+    private final M manager;
 
-    protected final List<SessionListener> listeners = new CopyOnWriteArrayList<>();
+    protected AbstractSessionFactory(M manager) {
+        this.manager = ValidateUtils.checkNotNull(manager, "No factory manager instance");
+    }
 
-    protected AbstractSessionFactory() {
-        super();
+    public M getFactoryManager() {
+        return manager;
     }
 
     @Override
-    protected AbstractSession createSession(IoSession ioSession) throws Exception {
-        AbstractSession session = doCreateSession(ioSession);
-
-        for (SessionListener l : listeners) {
-            l.sessionCreated(session);
-            session.addListener(l);
-        }
-
-        return session;
+    protected S createSession(IoSession ioSession) throws Exception {
+        return setupSession(doCreateSession(ioSession));
     }
 
-    protected abstract AbstractSession doCreateSession(IoSession ioSession) throws Exception;
+    protected abstract S doCreateSession(IoSession ioSession) throws Exception;
 
-    /**
-     * Add a session |listener|.
-     *
-     * @param listener the session listener to add
-     */
-    public void addListener(SessionListener listener) {
-        ValidateUtils.checkNotNull(listener, "addListener(%s) no listener", this);
-        this.listeners.add(listener);
-    }
-
-    /**
-     * Remove a session |listener|.
-     *
-     * @param listener the session listener to remove
-     */
-    public void removeListener(SessionListener listener) {
-        this.listeners.remove(listener);
+    protected S setupSession(S session) throws Exception {
+        FactoryManager listenersManager = getFactoryManager();
+        SessionListener sessionListener = listenersManager.getSessionListenerProxy();
+        // Inform the listener of the newly created session
+        sessionListener.sessionCreated(session);
+        // Delegate the task of further notifications to the session
+        session.addSessionListener(sessionListener);
+        session.addChannelListener(listenersManager.getChannelListenerProxy());
+        return session;
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
index 66616af..ec35195 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
@@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.common.Service;
+import org.apache.sshd.common.channel.ChannelListenerManager;
 import org.apache.sshd.common.future.SshFuture;
 import org.apache.sshd.common.io.IoSession;
 import org.apache.sshd.common.io.IoWriteFuture;
@@ -36,7 +37,7 @@ import org.apache.sshd.common.util.buffer.Buffer;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface Session extends Closeable {
+public interface Session extends SessionListenerManager, ChannelListenerManager, Closeable {
 
     /**
      * Timeout status.
@@ -181,20 +182,6 @@ public interface Session extends Closeable {
     void exceptionCaught(Throwable t);
 
     /**
-     * Add a session |listener|.
-     *
-     * @param listener the session listener to add
-     */
-    void addListener(SessionListener listener);
-
-    /**
-     * Remove a session |listener|.
-     *
-     * @param listener the session listener to remove
-     */
-    void removeListener(SessionListener listener);
-
-    /**
      * Initiate a new key exchange.
      *
      * @return An {@link SshFuture} for awaiting the completion of the exchange

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/main/java/org/apache/sshd/common/session/SessionListenerManager.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/SessionListenerManager.java b/sshd-core/src/main/java/org/apache/sshd/common/session/SessionListenerManager.java
new file mode 100644
index 0000000..eda580a
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/SessionListenerManager.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.common.session;
+
+/**
+ * Marker interface for classes that allow to add/remove session listeners.
+ * <B>Note:</B> if adding/removing listeners while connections are being
+ * established and/or torn down there are no guarantees as to the order of
+ * the calls to the recently added/removed listener's methods in the interim.
+ * The correct order is guaranteed only as of the <U>next</U> session after
+ * the listener has been added/removed.
+ *
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public interface SessionListenerManager {
+    /**
+     * Add a session listener.
+     *
+     * @param listener The {@link SessionListener} to add - not {@code null}
+     */
+    void addSessionListener(SessionListener listener);
+
+    /**
+     * Remove a session listener.
+     *
+     * @param listener The {@link SessionListener} to remove
+     */
+    void removeSessionListener(SessionListener listener);
+
+    /**
+     * @return A (never {@code null} proxy {@link SessionListener} that represents
+     * all the currently registered listeners. Any method invocation on the proxy
+     * is replicated to the currently registered listeners
+     */
+    SessionListener getSessionListenerProxy();
+}