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 2016/02/09 16:32:46 UTC

mina-sshd git commit: Lazy load forwarding support in AbstractConnectionService

Repository: mina-sshd
Updated Branches:
  refs/heads/master dae3a5679 -> c44b07b55


Lazy load forwarding support in AbstractConnectionService


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

Branch: refs/heads/master
Commit: c44b07b556dbd274e82f85963d9b5c8d46397984
Parents: dae3a56
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Tue Feb 9 17:32:21 2016 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Tue Feb 9 17:32:21 2016 +0200

----------------------------------------------------------------------
 .../sshd/agent/common/AgentForwardSupport.java  |  71 +-----
 .../common/DefaultAgentForwardSupport.java      | 114 ++++++++++
 .../client/session/ClientConnectionService.java |   8 +-
 .../session/AbstractConnectionService.java      |  95 ++++++--
 .../sshd/common/session/ConnectionService.java  |   6 +-
 .../sshd/server/channel/ChannelSession.java     |  22 +-
 .../server/session/ServerConnectionService.java |  13 --
 .../server/x11/DefaultX11ForwardSupport.java    | 226 +++++++++++++++++++
 .../sshd/server/x11/X11ForwardSupport.java      | 219 ++----------------
 9 files changed, 477 insertions(+), 297 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/agent/common/AgentForwardSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/common/AgentForwardSupport.java b/sshd-core/src/main/java/org/apache/sshd/agent/common/AgentForwardSupport.java
index a52dcb5..93ff21d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/agent/common/AgentForwardSupport.java
+++ b/sshd-core/src/main/java/org/apache/sshd/agent/common/AgentForwardSupport.java
@@ -20,67 +20,20 @@ package org.apache.sshd.agent.common;
 
 import java.io.IOException;
 
-import org.apache.sshd.agent.SshAgentFactory;
-import org.apache.sshd.agent.SshAgentServer;
-import org.apache.sshd.common.FactoryManager;
-import org.apache.sshd.common.SshException;
-import org.apache.sshd.common.session.ConnectionService;
-import org.apache.sshd.common.session.Session;
-import org.apache.sshd.common.util.ValidateUtils;
-import org.apache.sshd.common.util.closeable.AbstractCloseable;
+import org.apache.sshd.common.Closeable;
 
 /**
  * The server side fake agent, acting as an agent, but actually forwarding the requests to the auth channel on the client side.
  */
-public class AgentForwardSupport extends AbstractCloseable {
-
-    private final ConnectionService service;
-    private String agentId;
-    private SshAgentServer agentServer;
-
-    public AgentForwardSupport(ConnectionService service) {
-        this.service = service;
-    }
-
-    public String initialize() throws IOException {
-        try {
-            if (agentId == null) {
-                Session session = ValidateUtils.checkNotNull(service.getSession(), "No session");
-                FactoryManager manager = ValidateUtils.checkNotNull(session.getFactoryManager(), "No session factory manager");
-                SshAgentFactory factory = ValidateUtils.checkNotNull(manager.getAgentFactory(), "No agent factory");
-                agentServer = ValidateUtils.checkNotNull(factory.createServer(service), "No agent server created");
-                agentId = agentServer.getId();
-            }
-            return agentId;
-        } catch (IOException e) {
-            throw e;
-        } catch (Exception e) {
-            throw new SshException(e);
-        }
-    }
-
-    @Override
-    public synchronized void close() throws IOException {
-        if (agentId != null) {
-            agentId = null;
-            agentServer.close();
-            agentServer = null;
-        }
-    }
-
-    @Override
-    protected void doCloseImmediately() {
-        try {
-            close();
-        } catch (IOException e) {
-            throw new RuntimeException("Failed (" + e.getClass().getSimpleName() + ") to close agent: " + e.getMessage(), e);
-        }
-        super.doCloseImmediately();
-    }
-
-    @Override
-    public String toString() {
-        return getClass().getSimpleName() + "[" + service.getSession() + "]";
-    }
-
+public interface AgentForwardSupport extends Closeable {
+    /**
+     * Initializes the agent forwarding if not already done so - i.e.,
+     * can be called more than once - only first successful call counts,
+     * the rest will return the identifier of the previously initialized
+     * agent.
+     *
+     * @return The agent ID
+     * @throws IOException If failed to initialize
+     */
+    String initialize() throws IOException;
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/agent/common/DefaultAgentForwardSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/common/DefaultAgentForwardSupport.java b/sshd-core/src/main/java/org/apache/sshd/agent/common/DefaultAgentForwardSupport.java
new file mode 100644
index 0000000..fbbdbcc
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/agent/common/DefaultAgentForwardSupport.java
@@ -0,0 +1,114 @@
+/*
+ * 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.agent.common;
+
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.sshd.agent.SshAgentFactory;
+import org.apache.sshd.agent.SshAgentServer;
+import org.apache.sshd.common.FactoryManager;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.session.ConnectionService;
+import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.util.ValidateUtils;
+import org.apache.sshd.common.util.closeable.AbstractCloseable;
+
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class DefaultAgentForwardSupport extends AbstractCloseable implements AgentForwardSupport {
+
+    private final ConnectionService serviceInstance;
+    private final AtomicReference<SshAgentServer> agentServerHolder = new AtomicReference<>();
+
+    public DefaultAgentForwardSupport(ConnectionService service) {
+        serviceInstance = ValidateUtils.checkNotNull(service, "No connection service");
+    }
+
+    @Override
+    public String initialize() throws IOException {
+        Session session = serviceInstance.getSession();
+        try {
+            SshAgentServer agentServer;
+            synchronized (agentServerHolder) {
+                agentServer = agentServerHolder.get();
+                if (agentServer != null) {
+                    return agentServer.getId();
+                }
+
+                agentServer = ValidateUtils.checkNotNull(createSshAgentServer(serviceInstance, session), "No agent server created");
+                agentServerHolder.set(agentServer);
+            }
+
+            String agentId = agentServer.getId();
+            if (log.isDebugEnabled()) {
+                log.debug("initialize({}) id={}, server={}", session, agentId, agentServer);
+            }
+
+            return agentId;
+        } catch (Throwable t) {
+            if (log.isDebugEnabled()) {
+                log.debug("initialize({}) failed ({}) to create server: {}",
+                          session, t.getClass().getSimpleName(), t.getMessage());
+            }
+            if (log.isTraceEnabled()) {
+                log.trace("initialize(" + session + ") server creation failure details", t);
+            }
+            if (t instanceof IOException) {
+                throw (IOException) t;
+            } else {
+                throw new SshException(t);
+            }
+        }
+    }
+
+    protected SshAgentServer createSshAgentServer(ConnectionService service, Session session) throws Throwable {
+        FactoryManager manager = ValidateUtils.checkNotNull(session.getFactoryManager(), "No session factory manager");
+        SshAgentFactory factory = ValidateUtils.checkNotNull(manager.getAgentFactory(), "No agent factory");
+        return factory.createServer(service);
+    }
+
+    @Override
+    public void close() throws IOException {
+        SshAgentServer agentServer = agentServerHolder.getAndSet(null);
+        if (agentServer != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("close({}) closing server={}", serviceInstance.getSession(), agentServer);
+            }
+            agentServer.close();
+        }
+    }
+
+    @Override
+    protected void doCloseImmediately() {
+        try {
+            close();
+        } catch (IOException e) {
+            throw new RuntimeException("Failed (" + e.getClass().getSimpleName() + ") to close agent: " + e.getMessage(), e);
+        }
+        super.doCloseImmediately();
+    }
+
+    @Override
+    public String toString() {
+        return getClass().getSimpleName() + "[" + serviceInstance.getSession() + "]";
+    }
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
index 85ddb97..fff23fd 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
@@ -22,6 +22,7 @@ import java.io.IOException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
+import org.apache.sshd.agent.common.AgentForwardSupport;
 import org.apache.sshd.client.ClientFactoryManager;
 import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.common.PropertyResolverUtils;
@@ -29,6 +30,7 @@ import org.apache.sshd.common.SshConstants;
 import org.apache.sshd.common.SshException;
 import org.apache.sshd.common.session.AbstractConnectionService;
 import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.server.x11.X11ForwardSupport;
 
 /**
  * Client side <code>ssh-connection</code> service.
@@ -87,15 +89,13 @@ public class ClientConnectionService extends AbstractConnectionService<AbstractC
         }
     }
 
-    // TODO: remove from interface
     @Override
-    public String initAgentForward() throws IOException {
+    public AgentForwardSupport getAgentForwardSupport() {
         throw new IllegalStateException("Server side operation");
     }
 
-    // TODO: remove from interface
     @Override
-    public String createX11Display(boolean singleConnection, String authenticationProtocol, String authenticationCookie, int screen) throws IOException {
+    public X11ForwardSupport getX11ForwardSupport() {
         throw new IllegalStateException("Server side operation");
     }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractConnectionService.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractConnectionService.java
index 993f99a..b3696fc 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractConnectionService.java
@@ -25,8 +25,10 @@ import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.sshd.agent.common.AgentForwardSupport;
+import org.apache.sshd.agent.common.DefaultAgentForwardSupport;
 import org.apache.sshd.client.channel.AbstractClientChannel;
 import org.apache.sshd.client.future.OpenFuture;
 import org.apache.sshd.common.Closeable;
@@ -48,6 +50,7 @@ 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.closeable.AbstractInnerCloseable;
+import org.apache.sshd.server.x11.DefaultX11ForwardSupport;
 import org.apache.sshd.server.x11.X11ForwardSupport;
 
 /**
@@ -83,26 +86,15 @@ public abstract class AbstractConnectionService<S extends AbstractSession> exten
      */
     protected final AtomicInteger nextChannelId = new AtomicInteger(0);
 
-    /**
-     * The tcpip forwarder
-     */
-    protected final TcpipForwarder tcpipForwarder;
-    protected final AgentForwardSupport agentForward;
-    protected final X11ForwardSupport x11Forward;
+    private final AtomicReference<AgentForwardSupport> agentForwardHolder = new AtomicReference<>();
+    private final AtomicReference<X11ForwardSupport> x11ForwardHolder = new AtomicReference<>();
+    private final AtomicReference<TcpipForwarder> tcpipForwarderHolder = new AtomicReference<>();
     private final AtomicBoolean allowMoreSessions = new AtomicBoolean(true);
 
     private final S sessionInstance;
 
     protected AbstractConnectionService(S session) {
         sessionInstance = ValidateUtils.checkNotNull(session, "No session");
-        agentForward = new AgentForwardSupport(this);
-        x11Forward = new X11ForwardSupport(this);
-
-        FactoryManager manager =
-                ValidateUtils.checkNotNull(session.getFactoryManager(), "No factory manager");
-        TcpipForwarderFactory factory =
-                ValidateUtils.checkNotNull(manager.getTcpipForwarderFactory(), "No forwarder factory");
-        tcpipForwarder = ValidateUtils.checkNotNull(factory.create(this), "No forwarder created for %s", session);
     }
 
     public Collection<Channel> getChannels() {
@@ -121,13 +113,84 @@ public abstract class AbstractConnectionService<S extends AbstractSession> exten
 
     @Override
     public TcpipForwarder getTcpipForwarder() {
-        return tcpipForwarder;
+        TcpipForwarder forwarder;
+        S session = getSession();
+        synchronized (tcpipForwarderHolder) {
+            forwarder = tcpipForwarderHolder.get();
+            if (forwarder != null) {
+                return forwarder;
+            }
+
+            forwarder = ValidateUtils.checkNotNull(createTcpipForwarder(session), "No forwarder created for %s", session);
+            tcpipForwarderHolder.set(forwarder);
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("getTcpipForwarder({}) created instance", session);
+        }
+        return forwarder;
+    }
+
+    protected TcpipForwarder createTcpipForwarder(S session) {
+        FactoryManager manager =
+                ValidateUtils.checkNotNull(session.getFactoryManager(), "No factory manager");
+        TcpipForwarderFactory factory =
+                ValidateUtils.checkNotNull(manager.getTcpipForwarderFactory(), "No forwarder factory");
+        return factory.create(this);
+    }
+
+    @Override
+    public X11ForwardSupport getX11ForwardSupport() {
+        X11ForwardSupport x11Support;
+        S session = getSession();
+        synchronized (x11ForwardHolder) {
+            x11Support = x11ForwardHolder.get();
+            if (x11Support != null) {
+                return x11Support;
+            }
+
+            x11Support = ValidateUtils.checkNotNull(createX11ForwardSupport(session), "No X11 forwarder created for %s", session);
+            x11ForwardHolder.set(x11Support);
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("getX11ForwardSupport({}) created instance", session);
+        }
+        return x11Support;
+    }
+
+    protected X11ForwardSupport createX11ForwardSupport(S session) {
+        return new DefaultX11ForwardSupport(this);
+    }
+
+    @Override
+    public AgentForwardSupport getAgentForwardSupport() {
+        AgentForwardSupport agentForward;
+        S session = getSession();
+        synchronized (agentForwardHolder) {
+            agentForward = agentForwardHolder.get();
+            if (agentForward != null) {
+                return agentForward;
+            }
+
+            agentForward = ValidateUtils.checkNotNull(createAgentForwardSupport(session), "No agent forward created for %s", session);
+            agentForwardHolder.set(agentForward);
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("getAgentForwardSupport({}) created instance", session);
+        }
+        return agentForward;
+    }
+
+    protected AgentForwardSupport createAgentForwardSupport(S session) {
+        return new DefaultAgentForwardSupport(this);
     }
 
     @Override
     protected Closeable getInnerCloseable() {
         return builder()
-                .sequential(getTcpipForwarder(), agentForward, x11Forward)
+                .sequential(tcpipForwarderHolder.get(), agentForwardHolder.get(), x11ForwardHolder.get())
                 .parallel(channels.values())
                 .build();
     }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionService.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionService.java
index 638c2d1..c0b695c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/ConnectionService.java
@@ -20,9 +20,11 @@ package org.apache.sshd.common.session;
 
 import java.io.IOException;
 
+import org.apache.sshd.agent.common.AgentForwardSupport;
 import org.apache.sshd.common.Service;
 import org.apache.sshd.common.channel.Channel;
 import org.apache.sshd.common.forward.TcpipForwarder;
+import org.apache.sshd.server.x11.X11ForwardSupport;
 
 /**
  * Interface implementing ssh-connection service.
@@ -54,10 +56,10 @@ public interface ConnectionService extends Service {
     TcpipForwarder getTcpipForwarder();
 
     // TODO: remove from interface, it's server side only
-    String initAgentForward() throws IOException;
+    AgentForwardSupport getAgentForwardSupport();
 
     // TODO: remove from interface, it's server side only
-    String createX11Display(boolean singleConnection, String authenticationProtocol, String authenticationCookie, int screen) throws IOException;
+    X11ForwardSupport getX11ForwardSupport();
 
     boolean isAllowMoreSessions();
     void setAllowMoreSessions(boolean allow);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java b/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java
index 2f31080..4fdc044 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/channel/ChannelSession.java
@@ -30,6 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.sshd.agent.SshAgent;
 import org.apache.sshd.agent.SshAgentFactory;
+import org.apache.sshd.agent.common.AgentForwardSupport;
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.Factory;
 import org.apache.sshd.common.FactoryManager;
@@ -698,7 +699,15 @@ public class ChannelSession extends AbstractServerChannel {
             throw new RuntimeSshException(e);
         }
 
-        String authSocket = service.initAgentForward();
+        AgentForwardSupport agentForward = service.getAgentForwardSupport();
+        if (agentForward == null) {
+            if (log.isDebugEnabled()) {
+                log.debug("handleAgentForwarding() no agent forward support", this);
+            }
+            return RequestHandler.Result.ReplyFailure;
+        }
+
+        String authSocket = agentForward.initialize();
         addEnvVariable(SshAgent.SSH_AUTHSOCKET_ENV_NAME, authSocket);
         return RequestHandler.Result.ReplySuccess;
     }
@@ -729,7 +738,16 @@ public class ChannelSession extends AbstractServerChannel {
             throw new RuntimeSshException(e);
         }
 
-        String display = service.createX11Display(singleConnection, authProtocol, authCookie, screenId);
+        X11ForwardSupport x11Forward = service.getX11ForwardSupport();
+        if (x11Forward == null) {
+            if (log.isDebugEnabled()) {
+                log.debug("handleX11Forwarding({}) single={}, protocol={}, cookie={}, screen={} - no forwarder'",
+                          this, singleConnection, authProtocol, authCookie, screenId);
+            }
+            return RequestHandler.Result.ReplyFailure;
+        }
+
+        String display = x11Forward.createDisplay(singleConnection, authProtocol, authCookie, screenId);
         if (log.isDebugEnabled()) {
             log.debug("handleX11Forwarding({}) single={}, protocol={}, cookie={}, screen={} - display='{}'",
                       this, singleConnection, authProtocol, authCookie, screenId, display);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/server/session/ServerConnectionService.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerConnectionService.java
index 97e96b8..6859356 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerConnectionService.java
@@ -18,8 +18,6 @@
  */
 package org.apache.sshd.server.session;
 
-import java.io.IOException;
-
 import org.apache.sshd.common.SshException;
 import org.apache.sshd.common.session.AbstractConnectionService;
 
@@ -41,15 +39,4 @@ public class ServerConnectionService extends AbstractConnectionService<AbstractS
     public final ServerSession getServerSession() {
         return getSession();
     }
-
-    @Override
-    public String initAgentForward() throws IOException {
-        return agentForward.initialize();
-    }
-
-    @Override
-    public String createX11Display(boolean singleConnection, String authenticationProtocol, String authenticationCookie, int screen) throws IOException {
-        return x11Forward.createDisplay(singleConnection, authenticationProtocol, authenticationCookie, screen);
-    }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/server/x11/DefaultX11ForwardSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/x11/DefaultX11ForwardSupport.java b/sshd-core/src/main/java/org/apache/sshd/server/x11/DefaultX11ForwardSupport.java
new file mode 100644
index 0000000..3e02e80
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/server/x11/DefaultX11ForwardSupport.java
@@ -0,0 +1,226 @@
+/*
+ * 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.server.x11;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.BindException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Collection;
+
+import org.apache.sshd.common.Closeable;
+import org.apache.sshd.common.FactoryManager;
+import org.apache.sshd.common.PropertyResolverUtils;
+import org.apache.sshd.common.io.IoAcceptor;
+import org.apache.sshd.common.io.IoServiceFactory;
+import org.apache.sshd.common.io.IoSession;
+import org.apache.sshd.common.session.ConnectionService;
+import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.OsUtils;
+import org.apache.sshd.common.util.Readable;
+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.common.util.closeable.AbstractInnerCloseable;
+
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class DefaultX11ForwardSupport extends AbstractInnerCloseable implements X11ForwardSupport {
+
+    private final ConnectionService service;
+    private IoAcceptor acceptor;
+
+    public DefaultX11ForwardSupport(ConnectionService service) {
+        this.service = ValidateUtils.checkNotNull(service, "No connection service");
+    }
+
+    @Override
+    public void close() throws IOException {
+        close(true);
+    }
+
+    @Override
+    protected Closeable getInnerCloseable() {
+        return builder().close(acceptor).build();
+    }
+
+    // TODO consider reducing the 'synchronized' section to specific code locations rather than entire method
+    @Override
+    public synchronized String createDisplay(
+            boolean singleConnection, String authenticationProtocol, String authenticationCookie, int screen)
+                    throws IOException {
+        if (isClosed()) {
+            throw new IllegalStateException("X11ForwardSupport is closed");
+        }
+        if (isClosing()) {
+            throw new IllegalStateException("X11ForwardSupport is closing");
+        }
+
+        // only support non windows systems
+        if (OsUtils.isWin32()) {
+            if (log.isDebugEnabled()) {
+                log.debug("createDisplay(auth={}, cookie={}, screen={}) Windows O/S N/A",
+                          authenticationProtocol, authenticationCookie, screen);
+            }
+            return null;
+        }
+
+        Session session = ValidateUtils.checkNotNull(service.getSession(), "No session");
+        if (acceptor == null) {
+            FactoryManager manager = ValidateUtils.checkNotNull(session.getFactoryManager(), "No factory manager");
+            IoServiceFactory factory = ValidateUtils.checkNotNull(manager.getIoServiceFactory(), "No I/O service factory");
+            acceptor = factory.createAcceptor(this);
+        }
+
+        int minDisplayNumber = PropertyResolverUtils.getIntProperty(session, X11_DISPLAY_OFFSET, DEFAULT_X11_DISPLAY_OFFSET);
+        int maxDisplayNumber = PropertyResolverUtils.getIntProperty(session, X11_MAX_DISPLAYS, DEFAULT_X11_MAX_DISPLAYS);
+        int basePort = PropertyResolverUtils.getIntProperty(session, X11_BASE_PORT, DEFAULT_X11_BASE_PORT);
+        String bindHost = PropertyResolverUtils.getStringProperty(session, X11_BIND_HOST, DEFAULT_X11_BIND_HOST);
+        InetSocketAddress addr = null;
+
+        // try until bind successful or max is reached
+        for (int displayNumber = minDisplayNumber; displayNumber < maxDisplayNumber; displayNumber++) {
+            int port = basePort + displayNumber;
+            addr = new InetSocketAddress(bindHost, port);
+            try {
+                acceptor.bind(addr);
+                break;
+            } catch (BindException bindErr) {
+                if (log.isDebugEnabled()) {
+                    log.debug("createDisplay(auth={}, cookie={}, screen={}) failed ({}) to bind to address={}: {}",
+                              authenticationProtocol, authenticationCookie, screen,
+                              bindErr.getClass().getSimpleName(), addr, bindErr.getMessage());
+                }
+
+                addr = null;
+            }
+        }
+
+        if (addr == null) {
+            log.warn("createDisplay(auth={}, cookie={}, screen={})"
+                   + " failed to allocate internet-domain X11 display socket in range {}-{}",
+                     authenticationProtocol, authenticationCookie, screen,
+                     minDisplayNumber, maxDisplayNumber);
+            Collection<SocketAddress> boundAddressess = acceptor.getBoundAddresses();
+            if (GenericUtils.isEmpty(boundAddressess)) {
+                if (log.isDebugEnabled()) {
+                    log.debug("createDisplay(auth={}, cookie={}, screen={}) closing - no more bound addresses",
+                              authenticationProtocol, authenticationCookie, screen);
+                }
+                close();
+            } else {
+                if (log.isDebugEnabled()) {
+                    log.debug("createDisplay(auth={}, cookie={}, screen={}) closing - remaining bound addresses: {}",
+                              authenticationProtocol, authenticationCookie, screen, boundAddressess);
+                }
+            }
+
+            return null;
+        }
+
+        int port = addr.getPort();
+        int displayNumber = port - basePort;
+        String authDisplay = "unix:" + displayNumber + "." + screen;
+        try {
+            Process p = new ProcessBuilder(XAUTH_COMMAND, "remove", authDisplay).start();
+            int result = p.waitFor();
+            if (log.isDebugEnabled()) {
+                log.debug("createDisplay({}) {} remove result={}", authDisplay, XAUTH_COMMAND, result);
+            }
+
+            if (result == 0) {
+                p = new ProcessBuilder(XAUTH_COMMAND, "add", authDisplay, authenticationProtocol, authenticationCookie).start();
+                result = p.waitFor();
+
+                if (log.isDebugEnabled()) {
+                    log.debug("createDisplay({}) {} add result={}", authDisplay, XAUTH_COMMAND, result);
+                }
+            }
+
+            if (result != 0) {
+                throw new IllegalStateException("Bad " + XAUTH_COMMAND + " invocation result: " + result);
+            }
+
+            return bindHost + ":" + displayNumber + "." + screen;
+        } catch (Throwable e) {
+            log.warn("createDisplay({}) failed ({}) run xauth: {}",
+                     authDisplay, e.getClass().getSimpleName(), e.getMessage());
+            if (log.isDebugEnabled()) {
+                log.debug("createDisplay(" + authDisplay + ") xauth failure details", e);
+            }
+            return null;
+        }
+    }
+
+    @Override
+    public void sessionCreated(IoSession session) throws Exception {
+        ChannelForwardedX11 channel = new ChannelForwardedX11(session);
+        session.setAttribute(ChannelForwardedX11.class, channel);
+        if (log.isDebugEnabled()) {
+            log.debug("sessionCreated({}) channel{}", session, channel);
+        }
+        this.service.registerChannel(channel);
+        channel.open().verify(PropertyResolverUtils.getLongProperty(channel, CHANNEL_OPEN_TIMEOUT_PROP, DEFAULT_CHANNEL_OPEN_TIMEOUT));
+    }
+
+    @Override
+    public void sessionClosed(IoSession session) throws Exception {
+        ChannelForwardedX11 channel = (ChannelForwardedX11) session.getAttribute(ChannelForwardedX11.class);
+        if (channel != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("sessionClosed({}) close channel={}", session, channel);
+            }
+            channel.close(false);
+        }
+    }
+
+    @Override
+    public void messageReceived(IoSession session, Readable message) throws Exception {
+        ChannelForwardedX11 channel = (ChannelForwardedX11) session.getAttribute(ChannelForwardedX11.class);
+        Buffer buffer = new ByteArrayBuffer(message.available() + Long.SIZE, false);
+        buffer.putBuffer(message);
+
+        if (log.isTraceEnabled()) {
+            log.trace("messageReceived({}) channel={}, len={}", session, channel, buffer.available());
+        }
+        OutputStream outputStream = channel.getInvertedIn();
+        outputStream.write(buffer.array(), buffer.rpos(), buffer.available());
+        outputStream.flush();
+    }
+
+    @Override
+    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
+        if (log.isDebugEnabled()) {
+            log.debug("exceptionCaught({}) {}: {}", session, cause.getClass().getSimpleName(), cause.getMessage());
+        }
+        if (log.isTraceEnabled()) {
+            log.trace("exceptionCaught(" + session + ") caught exception details", cause);
+        }
+        session.close(false);
+    }
+
+    @Override
+    public String toString() {
+        return getClass().getSimpleName() + ": " + service.getClass();
+    }
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/c44b07b5/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java b/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java
index 72091f4..c4eb337 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java
@@ -19,251 +19,68 @@
 package org.apache.sshd.server.x11;
 
 import java.io.IOException;
-import java.io.OutputStream;
-import java.net.BindException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.util.Collection;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.FactoryManager;
-import org.apache.sshd.common.PropertyResolverUtils;
-import org.apache.sshd.common.io.IoAcceptor;
 import org.apache.sshd.common.io.IoHandler;
-import org.apache.sshd.common.io.IoServiceFactory;
-import org.apache.sshd.common.io.IoSession;
-import org.apache.sshd.common.session.ConnectionService;
-import org.apache.sshd.common.session.Session;
-import org.apache.sshd.common.util.GenericUtils;
-import org.apache.sshd.common.util.OsUtils;
-import org.apache.sshd.common.util.Readable;
-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.common.util.closeable.AbstractInnerCloseable;
 import org.apache.sshd.common.util.net.SshdSocketAddress;
 
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public class X11ForwardSupport extends AbstractInnerCloseable implements IoHandler {
-
+public interface X11ForwardSupport extends Closeable, IoHandler {
     /**
      * Configuration value on the {@link FactoryManager} to control the
      * channel open timeout. If not specified then {@link #DEFAULT_CHANNEL_OPEN_TIMEOUT}
      * value is used
      */
-    public static final String CHANNEL_OPEN_TIMEOUT_PROP = "x11-fwd-open-timeout";
-    public static final long DEFAULT_CHANNEL_OPEN_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);
+    String CHANNEL_OPEN_TIMEOUT_PROP = "x11-fwd-open-timeout";
+    long DEFAULT_CHANNEL_OPEN_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);
 
     /**
      * Configuration value to control from which X11 display number to start
      * looking for a free value. If not specified, then {@link #DEFAULT_X11_DISPLAY_OFFSET}
      * is used
      */
-    public static final String X11_DISPLAY_OFFSET = "x11-fwd-display-offset";
-    public static final int DEFAULT_X11_DISPLAY_OFFSET = 10;
+    String X11_DISPLAY_OFFSET = "x11-fwd-display-offset";
+    int DEFAULT_X11_DISPLAY_OFFSET = 10;
 
     /**
      * Configuration value to control up to which (but not including) X11 display number
      * to look or a free value. If not specified, then {@link #DEFAULT_X11_MAX_DISPLAYS}
      * is used
      */
-    public static final String X11_MAX_DISPLAYS = "x11-fwd-max-display";
-    public static final int DEFAULT_X11_MAX_DISPLAYS = 1000;
+    String X11_MAX_DISPLAYS = "x11-fwd-max-display";
+    int DEFAULT_X11_MAX_DISPLAYS = 1000;
 
     /**
      * Configuration value to control the base port number for the X11 display
      * number socket binding. If not specified then {@link #DEFAULT_X11_BASE_PORT}
      * value is used
      */
-    public static final String X11_BASE_PORT = "x11-fwd-base-port";
-    public static final int DEFAULT_X11_BASE_PORT = 6000;
+    String X11_BASE_PORT = "x11-fwd-base-port";
+    int DEFAULT_X11_BASE_PORT = 6000;
 
     /**
      * Configuration value to control the host used to bind to for the X11 display
      * when looking for a free port. If not specified, then {@link #DEFAULT_X11_BIND_HOST}
      * is used
      */
-    public static final String X11_BIND_HOST = "x11-fwd-bind-host";
-    public static final String DEFAULT_X11_BIND_HOST = SshdSocketAddress.LOCALHOST_IP;
+    String X11_BIND_HOST = "x11-fwd-bind-host";
+    String DEFAULT_X11_BIND_HOST = SshdSocketAddress.LOCALHOST_IP;
 
     /**
      * Key for the user DISPLAY variable
      */
-    public static final String ENV_DISPLAY = "DISPLAY";
-
-    public static final String XAUTH_COMMAND = System.getProperty("sshd.XAUTH_COMMAND", "xauth");
-
-    private final ConnectionService service;
-    private IoAcceptor acceptor;
+    String ENV_DISPLAY = "DISPLAY";
 
-    public X11ForwardSupport(ConnectionService service) {
-        this.service = service;
-    }
-
-    @Override
-    public void close() throws IOException {
-        close(true);
-    }
-
-    @Override
-    protected Closeable getInnerCloseable() {
-        return builder().close(acceptor).build();
-    }
+    /**
+     * &quot;xauth&quot; command name
+     */
+    String XAUTH_COMMAND = System.getProperty("sshd.XAUTH_COMMAND", "xauth");
 
-    // TODO consider reducing the 'synchronized' section to specific code locations rather than entire method
-    public synchronized String createDisplay(
+    String createDisplay(
             boolean singleConnection, String authenticationProtocol, String authenticationCookie, int screen)
-                    throws IOException {
-        if (isClosed()) {
-            throw new IllegalStateException("X11ForwardSupport is closed");
-        }
-        if (isClosing()) {
-            throw new IllegalStateException("X11ForwardSupport is closing");
-        }
-
-        // only support non windows systems
-        if (OsUtils.isWin32()) {
-            if (log.isDebugEnabled()) {
-                log.debug("createDisplay(auth={}, cookie={}, screen={}) Windows O/S N/A",
-                          authenticationProtocol, authenticationCookie, screen);
-            }
-            return null;
-        }
-
-        Session session = ValidateUtils.checkNotNull(service.getSession(), "No session");
-        if (acceptor == null) {
-            FactoryManager manager = ValidateUtils.checkNotNull(session.getFactoryManager(), "No factory manager");
-            IoServiceFactory factory = ValidateUtils.checkNotNull(manager.getIoServiceFactory(), "No I/O service factory");
-            acceptor = factory.createAcceptor(this);
-        }
-
-        int minDisplayNumber = PropertyResolverUtils.getIntProperty(session, X11_DISPLAY_OFFSET, DEFAULT_X11_DISPLAY_OFFSET);
-        int maxDisplayNumber = PropertyResolverUtils.getIntProperty(session, X11_MAX_DISPLAYS, DEFAULT_X11_MAX_DISPLAYS);
-        int basePort = PropertyResolverUtils.getIntProperty(session, X11_BASE_PORT, DEFAULT_X11_BASE_PORT);
-        String bindHost = PropertyResolverUtils.getStringProperty(session, X11_BIND_HOST, DEFAULT_X11_BIND_HOST);
-        InetSocketAddress addr = null;
-
-        // try until bind successful or max is reached
-        for (int displayNumber = minDisplayNumber; displayNumber < maxDisplayNumber; displayNumber++) {
-            int port = basePort + displayNumber;
-            addr = new InetSocketAddress(bindHost, port);
-            try {
-                acceptor.bind(addr);
-                break;
-            } catch (BindException bindErr) {
-                if (log.isDebugEnabled()) {
-                    log.debug("createDisplay(auth={}, cookie={}, screen={}) failed ({}) to bind to address={}: {}",
-                              authenticationProtocol, authenticationCookie, screen,
-                              bindErr.getClass().getSimpleName(), addr, bindErr.getMessage());
-                }
-
-                addr = null;
-            }
-        }
-
-        if (addr == null) {
-            log.warn("createDisplay(auth={}, cookie={}, screen={})"
-                   + " failed to allocate internet-domain X11 display socket in range {}-{}",
-                     authenticationProtocol, authenticationCookie, screen,
-                     minDisplayNumber, maxDisplayNumber);
-            Collection<SocketAddress> boundAddressess = acceptor.getBoundAddresses();
-            if (GenericUtils.isEmpty(boundAddressess)) {
-                if (log.isDebugEnabled()) {
-                    log.debug("createDisplay(auth={}, cookie={}, screen={}) closing - no more bound addresses",
-                              authenticationProtocol, authenticationCookie, screen);
-                }
-                close();
-            } else {
-                if (log.isDebugEnabled()) {
-                    log.debug("createDisplay(auth={}, cookie={}, screen={}) closing - remaining bound addresses: {}",
-                              authenticationProtocol, authenticationCookie, screen, boundAddressess);
-                }
-            }
-
-            return null;
-        }
-
-        int port = addr.getPort();
-        int displayNumber = port - basePort;
-        String authDisplay = "unix:" + displayNumber + "." + screen;
-        try {
-            Process p = new ProcessBuilder(XAUTH_COMMAND, "remove", authDisplay).start();
-            int result = p.waitFor();
-            if (log.isDebugEnabled()) {
-                log.debug("createDisplay({}) {} remove result={}", authDisplay, XAUTH_COMMAND, result);
-            }
-
-            if (result == 0) {
-                p = new ProcessBuilder(XAUTH_COMMAND, "add", authDisplay, authenticationProtocol, authenticationCookie).start();
-                result = p.waitFor();
-
-                if (log.isDebugEnabled()) {
-                    log.debug("createDisplay({}) {} add result={}", authDisplay, XAUTH_COMMAND, result);
-                }
-            }
-
-            if (result != 0) {
-                throw new IllegalStateException("Bad " + XAUTH_COMMAND + " invocation result: " + result);
-            }
-
-            return bindHost + ":" + displayNumber + "." + screen;
-        } catch (Throwable e) {
-            log.warn("createDisplay({}) failed ({}) run xauth: {}",
-                     authDisplay, e.getClass().getSimpleName(), e.getMessage());
-            if (log.isDebugEnabled()) {
-                log.debug("createDisplay(" + authDisplay + ") xauth failure details", e);
-            }
-            return null;
-        }
-    }
-
-    @Override
-    public void sessionCreated(IoSession session) throws Exception {
-        ChannelForwardedX11 channel = new ChannelForwardedX11(session);
-        session.setAttribute(ChannelForwardedX11.class, channel);
-        if (log.isDebugEnabled()) {
-            log.debug("sessionCreated({}) channel{}", session, channel);
-        }
-        this.service.registerChannel(channel);
-        channel.open().verify(PropertyResolverUtils.getLongProperty(channel, CHANNEL_OPEN_TIMEOUT_PROP, DEFAULT_CHANNEL_OPEN_TIMEOUT));
-    }
-
-    @Override
-    public void sessionClosed(IoSession session) throws Exception {
-        ChannelForwardedX11 channel = (ChannelForwardedX11) session.getAttribute(ChannelForwardedX11.class);
-        if (channel != null) {
-            if (log.isDebugEnabled()) {
-                log.debug("sessionClosed({}) close channel={}", session, channel);
-            }
-            channel.close(false);
-        }
-    }
-
-    @Override
-    public void messageReceived(IoSession session, Readable message) throws Exception {
-        ChannelForwardedX11 channel = (ChannelForwardedX11) session.getAttribute(ChannelForwardedX11.class);
-        Buffer buffer = new ByteArrayBuffer(message.available() + Long.SIZE, false);
-        buffer.putBuffer(message);
-
-        if (log.isTraceEnabled()) {
-            log.trace("messageReceived({}) channel={}, len={}", session, channel, buffer.available());
-        }
-        OutputStream outputStream = channel.getInvertedIn();
-        outputStream.write(buffer.array(), buffer.rpos(), buffer.available());
-        outputStream.flush();
-    }
-
-    @Override
-    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
-        if (log.isDebugEnabled()) {
-            log.debug("exceptionCaught({}) {}: {}", session, cause.getClass().getSimpleName(), cause.getMessage());
-        }
-        if (log.isTraceEnabled()) {
-            log.trace("exceptionCaught(" + session + ") caught exception details", cause);
-        }
-        session.close(false);
-    }
+                    throws IOException;
 }