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/12/03 07:38:51 UTC

[1/7] mina-sshd git commit: [SSHD-605] VirtualFileSystemFactory allows escaping from root

Repository: mina-sshd
Updated Branches:
  refs/heads/master 484b793e4 -> 799f1cca4


[SSHD-605] VirtualFileSystemFactory allows escaping from root


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

Branch: refs/heads/master
Commit: d8487183302109c10f6ce7d8f5efb393049f9242
Parents: 484b793
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:32:31 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:32:31 2015 +0200

----------------------------------------------------------------------
 .../sshd/common/file/root/RootedFileSystem.java | 12 ++-
 .../file/root/RootedFileSystemProvider.java     | 96 ++++++++++++++++++--
 .../sshd/common/file/util/BaseFileSystem.java   | 32 +++++--
 .../apache/sshd/common/file/util/BasePath.java  | 38 ++++++--
 .../virtualfs/VirtualFileSystemFactory.java     | 50 +++++-----
 .../sshd/common/file/util/BasePathTest.java     | 57 ++++++------
 6 files changed, 210 insertions(+), 75 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/d8487183/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
index 05864ea..974667a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
@@ -28,6 +28,7 @@ import java.util.Set;
 
 import org.apache.sshd.common.file.util.BaseFileSystem;
 import org.apache.sshd.common.file.util.ImmutableList;
+import org.apache.sshd.common.util.ValidateUtils;
 
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
@@ -39,7 +40,7 @@ public class RootedFileSystem extends BaseFileSystem<RootedPath> {
 
     public RootedFileSystem(RootedFileSystemProvider fileSystemProvider, Path root, Map<String, ?> env) {
         super(fileSystemProvider);
-        this.rootPath = root;
+        this.rootPath = ValidateUtils.checkNotNull(root, "No root path");
         this.rootFs = root.getFileSystem();
     }
 
@@ -52,8 +53,15 @@ public class RootedFileSystem extends BaseFileSystem<RootedPath> {
     }
 
     @Override
+    public RootedFileSystemProvider provider() {
+        return (RootedFileSystemProvider) super.provider();
+    }
+
+    @Override
     public void close() throws IOException {
-        // ignored
+        if (log.isDebugEnabled()) {
+            log.debug("close({})", this);
+        }
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/d8487183/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
index 28cc00e..8068d18 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
@@ -34,6 +34,7 @@ import java.nio.file.FileSystem;
 import java.nio.file.FileSystemAlreadyExistsException;
 import java.nio.file.FileSystemNotFoundException;
 import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
 import java.nio.file.LinkOption;
 import java.nio.file.OpenOption;
 import java.nio.file.Path;
@@ -50,6 +51,8 @@ import java.util.concurrent.ExecutorService;
 
 import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.io.IoUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * File system provider which provides a rooted file system.
@@ -58,10 +61,11 @@ import org.apache.sshd.common.util.io.IoUtils;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public class RootedFileSystemProvider extends FileSystemProvider {
+    protected final Logger log;
     private final Map<Path, RootedFileSystem> fileSystems = new HashMap<>();
 
     public RootedFileSystemProvider() {
-        super();
+        log = LoggerFactory.getLogger(getClass());
     }
 
     @Override
@@ -99,6 +103,10 @@ public class RootedFileSystemProvider extends FileSystemProvider {
             throw new FileSystemAlreadyExistsException("newFileSystem(" + src + ") already mapped " + root);
         }
 
+        if (log.isTraceEnabled()) {
+            log.trace("newFileSystem({}): {}", src, rootedFs);
+        }
+
         return rootedFs;
     }
 
@@ -136,7 +144,11 @@ public class RootedFileSystemProvider extends FileSystemProvider {
 
         FileSystem fs = getFileSystem(uri);
         String subPath = str.substring(i + 1);
-        return fs.getPath(subPath);
+        Path p = fs.getPath(subPath);
+        if (log.isTraceEnabled()) {
+            log.trace("getPath({}): {}", uri, p);
+        }
+        return p;
     }
 
     @Override
@@ -217,11 +229,18 @@ public class RootedFileSystemProvider extends FileSystemProvider {
         } else {
             p.createLink(l, t);
         }
+
+        if (log.isDebugEnabled()) {
+            log.debug("createLink(symbolic={}) {} => {}", symLink, l, t);
+        }
     }
 
     @Override
     public void delete(Path path) throws IOException {
         Path r = unroot(path);
+        if (log.isTraceEnabled()) {
+            log.trace("delete({}): {}", path, r);
+        }
         FileSystemProvider p = provider(r);
         p.delete(r);
     }
@@ -229,6 +248,9 @@ public class RootedFileSystemProvider extends FileSystemProvider {
     @Override
     public boolean deleteIfExists(Path path) throws IOException {
         Path r = unroot(path);
+        if (log.isTraceEnabled()) {
+            log.trace("deleteIfExists({}): {}", path, r);
+        }
         FileSystemProvider p = provider(r);
         return p.deleteIfExists(r);
     }
@@ -237,13 +259,21 @@ public class RootedFileSystemProvider extends FileSystemProvider {
     public Path readSymbolicLink(Path link) throws IOException {
         Path r = unroot(link);
         FileSystemProvider p = provider(r);
-        return root((RootedFileSystem) link.getFileSystem(), p.readSymbolicLink(r));
+        Path t = p.readSymbolicLink(r);
+        Path target = root((RootedFileSystem) link.getFileSystem(), t);
+        if (log.isTraceEnabled()) {
+            log.trace("readSymbolicLink({})[{}]: {}[{}]", link, r, target, t);
+        }
+        return target;
     }
 
     @Override
     public void copy(Path source, Path target, CopyOption... options) throws IOException {
         Path s = unroot(source);
         Path t = unroot(target);
+        if (log.isTraceEnabled()) {
+            log.trace("copy({})[{}]: {}[{}]", source, s, target, t);
+        }
         FileSystemProvider p = provider(s);
         p.copy(s, t, options);
     }
@@ -252,6 +282,9 @@ public class RootedFileSystemProvider extends FileSystemProvider {
     public void move(Path source, Path target, CopyOption... options) throws IOException {
         Path s = unroot(source);
         Path t = unroot(target);
+        if (log.isTraceEnabled()) {
+            log.trace("move({})[{}]: {}[{}]", source, s, target, t);
+        }
         FileSystemProvider p = provider(s);
         p.move(s, t, options);
     }
@@ -306,6 +339,10 @@ public class RootedFileSystemProvider extends FileSystemProvider {
             throw new FileSystemNotFoundException(path.toString());
         }
 
+        if (log.isTraceEnabled()) {
+            log.trace("getFileSystem({}): {}", path, fsInstance);
+        }
+
         return fsInstance;
     }
 
@@ -326,6 +363,10 @@ public class RootedFileSystemProvider extends FileSystemProvider {
     @Override
     public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException {
         Path r = unroot(path);
+        if (log.isTraceEnabled()) {
+            log.trace("readAttributes({})[{}] type={}", path, r, type.getSimpleName());
+        }
+
         FileSystemProvider p = provider(r);
         return p.readAttributes(r, type, options);
     }
@@ -334,12 +375,19 @@ public class RootedFileSystemProvider extends FileSystemProvider {
     public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
         Path r = unroot(path);
         FileSystemProvider p = provider(r);
-        return p.readAttributes(r, attributes, options);
+        Map<String, Object> attrs = p.readAttributes(r, attributes, options);
+        if (log.isTraceEnabled()) {
+            log.trace("readAttributes({})[{}] {}: {}", path, r, attributes, attrs);
+        }
+        return attrs;
     }
 
     @Override
     public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
         Path r = unroot(path);
+        if (log.isTraceEnabled()) {
+            log.trace("setAttribute({})[{}] {}={}", path, r, attribute, value);
+        }
         FileSystemProvider p = provider(r);
         p.setAttribute(r, attribute, value, options);
     }
@@ -376,17 +424,47 @@ public class RootedFileSystemProvider extends FileSystemProvider {
 
         return resolveLocalPath((RootedPath) path);
     }
-    
+
     /**
      * @param path The original {@link RootedPath} - never {@code null}
      * @return The actual <U>absolute <B>local</B></U> {@link Path} represented
      * by the rooted one
+     * @throws InvalidPathException If the resolved path is not a proper sub-path
+     * of the rooted file system
      */
     protected Path resolveLocalPath(RootedPath path) {
-        Path absPath = path.toAbsolutePath();
-        String r = absPath.toString();
-        RootedFileSystem rfs = path.getFileSystem();
+        RootedPath absPath = ValidateUtils.checkNotNull(path, "No rooted path to resolve").toAbsolutePath();
+        RootedFileSystem rfs = absPath.getFileSystem();
         Path root = rfs.getRoot();
-        return root.resolve(r.substring(1));
+        FileSystem lfs = root.getFileSystem();
+
+        String rSep = ValidateUtils.checkNotNullAndNotEmpty(rfs.getSeparator(), "No rooted file system separator");
+        ValidateUtils.checkTrue(rSep.length() == 1, "Bad rooted file system separator: %s", rSep);
+        char rootedSeparator = rSep.charAt(0);
+
+        String lSep = ValidateUtils.checkNotNullAndNotEmpty(lfs.getSeparator(), "No local file system separator");
+        ValidateUtils.checkTrue(lSep.length() == 1, "Bad local file system separator: %s", lSep);
+        char localSeparator = lSep.charAt(0);
+
+        String r = absPath.toString();
+        String subPath = r.substring(1);
+        if (rootedSeparator != localSeparator) {
+            subPath = subPath.replace(rootedSeparator, localSeparator);
+        }
+
+        Path resolved = root.resolve(subPath);
+        if (log.isTraceEnabled()) {
+            log.trace("resolveLocalPath({}): {}", absPath, resolved);
+        }
+
+        /*
+         * This can happen for Windows since we represent its paths as /C:/some/path,
+         * so substring(1) yields C:/some/path - which is resolved as an absolute path
+         * (which we don't want).
+         */
+        if (!resolved.startsWith(root)) {
+            throw new InvalidPathException(r, "Not under root");
+        }
+        return resolved;
     }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/d8487183/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
index 3db927b..88c7c73 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
@@ -25,19 +25,24 @@ import java.nio.file.Path;
 import java.nio.file.PathMatcher;
 import java.nio.file.WatchService;
 import java.nio.file.spi.FileSystemProvider;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.ValidateUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public abstract class BaseFileSystem<T extends Path> extends FileSystem {
-
+    protected final Logger log;
     private final FileSystemProvider fileSystemProvider;
 
     public BaseFileSystem(FileSystemProvider fileSystemProvider) {
-        this.fileSystemProvider = fileSystemProvider;
+        this.log = LoggerFactory.getLogger(getClass());
+        this.fileSystemProvider = ValidateUtils.checkNotNull(fileSystemProvider, "No file system provider");
     }
 
     public T getDefaultDir() {
@@ -98,7 +103,12 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
         }
 
         String[] names = GenericUtils.split(path, '/');
-        return create(root, names);
+        T p = create(root, names);
+        if (log.isTraceEnabled()) {
+            log.trace("getPath({}, {}): {}", first, Arrays.toString(more), p);
+        }
+
+        return p;
     }
 
     protected void appendDedupSep(StringBuilder sb, CharSequence s) {
@@ -112,7 +122,7 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
 
     @Override
     public PathMatcher getPathMatcher(String syntaxAndPattern) {
-        int colonIndex = syntaxAndPattern.indexOf(':');
+        int colonIndex = ValidateUtils.checkNotNull(syntaxAndPattern, "No argument").indexOf(':');
         if ((colonIndex <= 0) || (colonIndex == syntaxAndPattern.length() - 1)) {
             throw new IllegalArgumentException("syntaxAndPattern must have form \"syntax:pattern\" but was \"" + syntaxAndPattern + "\"");
         }
@@ -130,6 +140,10 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
             default:
                 throw new UnsupportedOperationException("Unsupported path matcher syntax: \'" + syntax + "\'");
         }
+        if (log.isTraceEnabled()) {
+            log.trace("getPathMatcher({}): {}", syntaxAndPattern, expr);
+        }
+
         final Pattern regex = Pattern.compile(expr);
         return new PathMatcher() {
             @Override
@@ -141,7 +155,7 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
     }
 
     protected String globToRegex(String pattern) {
-        StringBuilder sb = new StringBuilder(pattern.length());
+        StringBuilder sb = new StringBuilder(ValidateUtils.checkNotNull(pattern, "No patern").length());
         int inGroup = 0;
         int inClass = 0;
         int firstIndexInClass = -1;
@@ -217,7 +231,13 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
                     sb.append(ch);
             }
         }
-        return sb.toString();
+
+        String regex = sb.toString();
+        if (log.isTraceEnabled()) {
+            log.trace("globToRegex({}): {}", pattern, regex);
+        }
+
+        return regex;
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/d8487183/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
index a630dbf..5f59626 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
@@ -45,6 +45,8 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
     protected final String root;
     protected final ImmutableList<String> names;
     private final FS fileSystem;
+    private String strValue;
+    private int hashValue;
 
     public BasePath(FS fileSystem, String root, ImmutableList<String> names) {
         this.fileSystem = ValidateUtils.checkNotNull(fileSystem, "No file system provided");
@@ -371,28 +373,44 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
 
     @Override
     public int hashCode() {
-        int hash = Objects.hashCode(getFileSystem());
-        // use hash codes from toString() form of names
-        hash = 31 * hash + Objects.hashCode(root);
-        for (String name : names) {
-            hash = 31 * hash + Objects.hashCode(name);
+        synchronized (this) {
+            if (hashValue == 0) {
+                hashValue = calculatedHashCode();
+                if (hashValue == 0) {
+                    hashValue = 1;
+                }
+            }
         }
-        return hash;
+
+        return hashValue;
+    }
+
+    protected int calculatedHashCode() {
+        return Objects.hash(getFileSystem(), root, names);
     }
 
     @Override
     public boolean equals(Object obj) {
-        return obj instanceof Path
-                && compareTo((Path) obj) == 0;
+        return (obj instanceof Path) && (compareTo((Path) obj) == 0);
     }
 
     @Override
     public String toString() {
+        synchronized (this) {
+            if (strValue == null) {
+                strValue = asString();
+            }
+        }
+
+        return strValue;
+    }
+
+    protected String asString() {
         StringBuilder sb = new StringBuilder();
         if (root != null) {
             sb.append(root);
         }
-        
+
         String separator = getFileSystem().getSeparator();
         for (String name : names) {
             if ((sb.length() > 0) && (sb.charAt(sb.length() - 1) != '/')) {
@@ -400,7 +418,7 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
             }
             sb.append(name);
         }
+
         return sb.toString();
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/d8487183/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java b/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
index 4370678..205d170 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
@@ -20,7 +20,8 @@ package org.apache.sshd.common.file.virtualfs;
 
 import java.io.IOException;
 import java.nio.file.FileSystem;
-import java.nio.file.Paths;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
 import java.util.Collections;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
@@ -28,53 +29,58 @@ import java.util.concurrent.ConcurrentHashMap;
 import org.apache.sshd.common.file.FileSystemFactory;
 import org.apache.sshd.common.file.root.RootedFileSystemProvider;
 import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.util.ValidateUtils;
 
 /**
  * SSHd file system factory to reduce the visibility to a physical folder.
  */
 public class VirtualFileSystemFactory implements FileSystemFactory {
 
-    private String defaultHomeDir;
-    private final Map<String, String> homeDirs = new ConcurrentHashMap<String, String>();
+    private Path defaultHomeDir;
+    private final Map<String, Path> homeDirs = new ConcurrentHashMap<String, Path>();
 
     public VirtualFileSystemFactory() {
+        super();
     }
 
-    public VirtualFileSystemFactory(String defaultHomeDir) {
+    public VirtualFileSystemFactory(Path defaultHomeDir) {
         this.defaultHomeDir = defaultHomeDir;
     }
 
-    public void setDefaultHomeDir(String defaultHomeDir) {
+    public void setDefaultHomeDir(Path defaultHomeDir) {
         this.defaultHomeDir = defaultHomeDir;
     }
 
-    public String getDefaultHomeDir() {
+    public Path getDefaultHomeDir() {
         return defaultHomeDir;
     }
 
-    public void setUserHomeDir(String userName, String userHomeDir) {
-        homeDirs.put(userName, userHomeDir);
+    public void setUserHomeDir(String userName, Path userHomeDir) {
+        homeDirs.put(ValidateUtils.checkNotNullAndNotEmpty(userName, "No username"),
+                     ValidateUtils.checkNotNull(userHomeDir, "No home dir"));
     }
 
-    public String getUserHomeDir(String userName) {
-        return homeDirs.get(userName);
+    public Path getUserHomeDir(String userName) {
+        return homeDirs.get(ValidateUtils.checkNotNullAndNotEmpty(userName, "No username"));
     }
 
-    protected String computeRootDir(String userName) {
-        String homeDir = homeDirs.get(userName);
-        if (homeDir == null) {
-            homeDir = defaultHomeDir;
+    @Override
+    public FileSystem createFileSystem(Session session) throws IOException {
+        String username = session.getUsername();
+        Path dir = computeRootDir(username);
+        if (dir == null) {
+            throw new InvalidPathException(username, "Cannot resolve home directory");
         }
+
+        return new RootedFileSystemProvider().newFileSystem(dir, Collections.<String, Object>emptyMap());
+    }
+
+    protected Path computeRootDir(String userName) throws IOException  {
+        Path homeDir = getUserHomeDir(userName);
         if (homeDir == null) {
-            throw new IllegalStateException("No home directory for user " + userName);
+            homeDir = getDefaultHomeDir();
         }
-        return homeDir;
-    }
 
-    @Override
-    public FileSystem createFileSystem(Session session) throws IOException {
-        String dir = computeRootDir(session.getUsername());
-        return new RootedFileSystemProvider().newFileSystem(Paths.get(dir), Collections.<String, Object>emptyMap());
+        return homeDir;
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/d8487183/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java b/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
index 4b8391f..00eb39e 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
@@ -36,19 +36,24 @@ import org.junit.Before;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
+import org.mockito.Mockito;
 
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class BasePathTest extends BaseTestSupport {
 
     private TestFileSystem fileSystem;
 
+    public BasePathTest() {
+        super();
+    }
+
     @Before
     public void setUp() {
-        fileSystem = new TestFileSystem(null);
+        fileSystem = new TestFileSystem(Mockito.mock(FileSystemProvider.class));
     }
 
     @Test
-    public void testPathParsing() {
+    public void testbasicPathParsing() {
         assertPathEquals("/", "/");
         assertPathEquals("/foo", "/foo");
         assertPathEquals("/foo", "/", "foo");
@@ -63,7 +68,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testPathParsing_withExtraSeparators() {
+    public void testPathParsingWithExtraSeparators() {
         assertPathEquals("/foo/bar", "///foo/bar");
         assertPathEquals("/foo/bar", "/foo///bar//");
         assertPathEquals("/foo/bar/baz", "/foo", "/bar", "baz/");
@@ -78,7 +83,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testRelativePath_singleName() {
+    public void testRelativePathSingleName() {
         new PathTester(fileSystem, "test")
                 .names("test")
                 .test("test");
@@ -88,7 +93,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testRelativePath_twoNames() {
+    public void testRelativePathTwoNames() {
         PathTester tester = new PathTester(fileSystem, "foo/bar")
                 .names("foo", "bar");
 
@@ -96,7 +101,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testRelativePath_fourNames() {
+    public void testRelativePathFourNames() {
         new PathTester(fileSystem, "foo/bar/baz/test")
                 .names("foo", "bar", "baz", "test")
                 .test("foo/bar/baz/test");
@@ -111,7 +116,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testAbsolutePath_twoNames() {
+    public void testAbsolutePathTwoNames() {
         new PathTester(fileSystem, "/foo/bar")
                 .root("/")
                 .names("foo", "bar")
@@ -119,7 +124,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testAbsoluteMultiNamePath_fourNames() {
+    public void testAbsoluteMultiNamePathFourNames() {
         new PathTester(fileSystem, "/foo/bar/baz/test")
                 .root("/")
                 .names("foo", "bar", "baz", "test")
@@ -127,7 +132,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolve_fromRoot() {
+    public void testResolveFromRoot() {
         Path root = parsePath("/");
 
         assertResolvedPathEquals("/foo", root, "foo");
@@ -138,7 +143,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolve_fromAbsolute() {
+    public void testResolveFromAbsolute() {
         Path path = parsePath("/foo");
 
         assertResolvedPathEquals("/foo/bar", path, "bar");
@@ -148,7 +153,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolve_fromRelative() {
+    public void testResolveFromRelative() {
         Path path = parsePath("foo");
 
         assertResolvedPathEquals("foo/bar", path, "bar");
@@ -158,7 +163,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolve_withThisAndParentDirNames() {
+    public void testResolveWithThisAndParentDirNames() {
         Path path = parsePath("/foo");
 
         assertResolvedPathEquals("/foo/bar/../baz", path, "bar/../baz");
@@ -168,7 +173,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolve_givenAbsolutePath() {
+    public void testResolveGivenAbsolutePath() {
         assertResolvedPathEquals("/test", parsePath("/foo"), "/test");
         assertResolvedPathEquals("/test", parsePath("foo"), "/test");
     }
@@ -180,12 +185,12 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolve_againstEmptyPath() {
+    public void testResolveAgainstEmptyPath() {
         assertResolvedPathEquals("foo/bar", parsePath(""), "foo/bar");
     }
 
     @Test
-    public void testResolveSibling_givenEmptyPath() {
+    public void testResolveSiblingGivenEmptyPath() {
         Path path = parsePath("foo/bar");
         Path resolved = path.resolveSibling("");
         assertPathEquals("foo", resolved);
@@ -196,7 +201,7 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testResolveSibling_againstEmptyPath() {
+    public void testResolveSiblingAgainstEmptyPath() {
         Path path = parsePath("");
         Path resolved = path.resolveSibling("foo");
         assertPathEquals("foo", resolved);
@@ -207,24 +212,24 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testRelativize_bothAbsolute() {
+    public void testRelativizeBothAbsolute() {
         assertRelativizedPathEquals("b/c", parsePath("/a"), "/a/b/c");
         assertRelativizedPathEquals("c/d", parsePath("/a/b"), "/a/b/c/d");
     }
 
     @Test
-    public void testRelativize_bothRelative() {
+    public void testRelativizeBothRelative() {
         assertRelativizedPathEquals("b/c", parsePath("a"), "a/b/c");
         assertRelativizedPathEquals("d", parsePath("a/b/c"), "a/b/c/d");
     }
 
     @Test
-    public void testRelativize_againstEmptyPath() {
+    public void testRelativizeAgainstEmptyPath() {
         assertRelativizedPathEquals("foo/bar", parsePath(""), "foo/bar");
     }
 
     @Test
-    public void testRelativize_oneAbsoluteOneRelative() {
+    public void testRelativizeOneAbsoluteOneRelative() {
         try {
             parsePath("/foo/bar").relativize(parsePath("foo"));
             fail();
@@ -241,34 +246,34 @@ public class BasePathTest extends BaseTestSupport {
     }
 
     @Test
-    public void testNormalize_withParentDirName() {
+    public void testNormalizeWithParentDirName() {
         assertNormalizedPathEquals("/foo/baz", "/foo/bar/../baz");
         assertNormalizedPathEquals("/foo/baz", "/foo", "bar", "..", "baz");
     }
 
     @Test
-    public void testNormalize_withThisDirName() {
+    public void testNormalizeWithThisDirName() {
         assertNormalizedPathEquals("/foo/bar/baz", "/foo/bar/./baz");
         assertNormalizedPathEquals("/foo/bar/baz", "/foo", "bar", ".", "baz");
     }
 
     @Test
-    public void testNormalize_withThisAndParentDirNames() {
+    public void testNormalizeWithThisAndParentDirNames() {
         assertNormalizedPathEquals("foo/test", "foo/./bar/../././baz/../test");
     }
 
     @Test
-    public void testNormalize_withLeadingParentDirNames() {
+    public void testNormalizeWithLeadingParentDirNames() {
         assertNormalizedPathEquals("../../foo/baz", "../../foo/bar/../baz");
     }
 
     @Test
-    public void testNormalize_withLeadingThisAndParentDirNames() {
+    public void testNormalizeWithLeadingThisAndParentDirNames() {
         assertNormalizedPathEquals("../../foo/baz", "./.././.././foo/bar/../baz");
     }
 
     @Test
-    public void testNormalize_withExtraParentDirNamesAtRoot() {
+    public void testNormalizeWithExtraParentDirNamesAtRoot() {
         assertNormalizedPathEquals("/", "/..");
         assertNormalizedPathEquals("/", "/../../..");
         assertNormalizedPathEquals("/", "/foo/../../..");


[6/7] mina-sshd git commit: Converted CompressionTest to @Parameterized

Posted by lg...@apache.org.
Converted CompressionTest to @Parameterized


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

Branch: refs/heads/master
Commit: 089624a8265daddb46689914504bbb0812f73edb
Parents: 844cd72
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:38:06 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:38:06 2015 +0200

----------------------------------------------------------------------
 .../common/compression/CompressionTest.java     | 56 ++++++++++++--------
 1 file changed, 33 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/089624a8/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java b/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java
index a3ca915..67c1987 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java
@@ -22,6 +22,7 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
+import java.util.List;
 
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.server.SshServer;
@@ -29,9 +30,15 @@ import org.apache.sshd.util.test.BaseTestSupport;
 import org.apache.sshd.util.test.JSchLogger;
 import org.apache.sshd.util.test.SimpleUserInfo;
 import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
 
 import com.jcraft.jsch.JSch;
 
@@ -41,34 +48,34 @@ import com.jcraft.jsch.JSch;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@RunWith(Parameterized.class)   // see https://github.com/junit-team/junit/wiki/Parameterized-tests
 public class CompressionTest extends BaseTestSupport {
+    @Parameters(name = "factory={0}")
+    public static List<Object[]> parameters() {
+        return parameterize(BuiltinCompressions.VALUES);
+    }
 
+    private final CompressionFactory factory;
     private SshServer sshd;
 
-    @Test
-    public void testCompNone() throws Exception {
-        setUp(BuiltinCompressions.none);
-        runTest();
-    }
-
-    @Test
-    public void testCompZlib() throws Exception {
-        setUp(BuiltinCompressions.zlib);
-        runTest();
+    public CompressionTest(CompressionFactory factory) {
+        this.factory = factory;
     }
 
-    @Test
-    public void testCompDelayedZlib() throws Exception {
-        setUp(BuiltinCompressions.delayedZlib);
-        runTest();
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
     }
 
-    protected void setUp(NamedFactory<org.apache.sshd.common.compression.Compression> compression) throws Exception {
+    @Before
+    public void setUp() throws Exception {
         sshd = setupTestServer();
-        sshd.setCompressionFactories(Arrays.<NamedFactory<org.apache.sshd.common.compression.Compression>>asList(compression));
+        sshd.setCompressionFactories(Arrays.<NamedFactory<org.apache.sshd.common.compression.Compression>>asList(factory));
         sshd.start();
-        JSch.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
-        JSch.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
+
+        String name = factory.getName();
+        JSch.setConfig("compression.s2c", name);
+        JSch.setConfig("compression.c2s", name);
         JSch.setConfig("zlib", com.jcraft.jsch.jcraft.Compression.class.getName());
         JSch.setConfig("zlib@openssh.com", com.jcraft.jsch.jcraft.Compression.class.getName());
     }
@@ -82,8 +89,10 @@ public class CompressionTest extends BaseTestSupport {
         JSch.setConfig("compression.c2s", "none");
     }
 
-    protected void runTest() throws Exception {
-        JSchLogger.init();
+    @Test
+    public void testCompression() throws Exception {
+        Assume.assumeTrue("Skip unsupported compression " + factory, factory.isSupported());
+
         JSch sch = new JSch();
         com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort());
         s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
@@ -94,10 +103,11 @@ public class CompressionTest extends BaseTestSupport {
             c.connect();
             try (OutputStream os = c.getOutputStream();
                  InputStream is = c.getInputStream()) {
-                final String STR = "this is my command\n";
-                final byte[] bytes = STR.getBytes(StandardCharsets.UTF_8);
+
+                String STR = "this is my command\n";
+                byte[] bytes = STR.getBytes(StandardCharsets.UTF_8);
                 byte[] data = new byte[bytes.length + Long.SIZE];
-                for (int i = 0; i < 10; i++) {
+                for (int i = 1; i <= 10; i++) {
                     os.write(bytes);
                     os.flush();
 


[3/7] mina-sshd git commit: Moved Jsch logger initialization to @BeforeClass

Posted by lg...@apache.org.
Moved Jsch logger initialization to @BeforeClass


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

Branch: refs/heads/master
Commit: 14eb57c19aa5900eceb673475cc69827c2b8f289
Parents: e5d6d80
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:35:49 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:35:49 2015 +0200

----------------------------------------------------------------------
 .../src/test/java/org/apache/sshd/KeyReExchangeTest.java      | 7 ++++++-
 .../src/test/java/org/apache/sshd/PortForwardingLoadTest.java | 7 ++++++-
 .../src/test/java/org/apache/sshd/PortForwardingTest.java     | 7 ++++++-
 .../test/java/org/apache/sshd/common/cipher/CipherTest.java   | 7 ++++++-
 .../test/java/org/apache/sshd/spring/SpringConfigTest.java    | 7 ++++++-
 .../java/org/apache/sshd/git/pack/GitPackCommandTest.java     | 7 ++++++-
 6 files changed, 36 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/14eb57c1/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
index 323e131..3362a4f 100644
--- a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
@@ -59,6 +59,7 @@ import org.apache.sshd.util.test.SimpleUserInfo;
 import org.apache.sshd.util.test.TeeOutputStream;
 import org.junit.After;
 import org.junit.Assume;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -80,6 +81,11 @@ public class KeyReExchangeTest extends BaseTestSupport {
         super();
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     @After
     public void tearDown() throws Exception {
         sshd.stop(true);
@@ -202,7 +208,6 @@ public class KeyReExchangeTest extends BaseTestSupport {
         Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
         setUp(0L, 0L, 0L);
 
-        JSchLogger.init();
         JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
         JSch sch = new JSch();
         com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/14eb57c1/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
index d5720a9..fe89fba 100644
--- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
@@ -53,6 +53,7 @@ import org.apache.sshd.util.test.SimpleUserInfo;
 import org.apache.sshd.util.test.Utils;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -78,6 +79,11 @@ public class PortForwardingLoadTest extends BaseTestSupport {
         super();
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     @Before
     public void setUp() throws Exception {
         sshd = setupTestServer();
@@ -389,7 +395,6 @@ public class PortForwardingLoadTest extends BaseTestSupport {
     }
 
     protected Session createSession() throws JSchException {
-        JSchLogger.init();
         JSch sch = new JSch();
         Session session = sch.getSession("sshd", TEST_LOCALHOST, sshPort);
         session.setUserInfo(new SimpleUserInfo("sshd"));

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/14eb57c1/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
index 490f884..3b5ddb2 100644
--- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
@@ -62,6 +62,7 @@ import org.apache.sshd.util.test.SimpleUserInfo;
 import org.apache.sshd.util.test.Utils;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -91,6 +92,11 @@ public class PortForwardingTest extends BaseTestSupport {
         super();
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     @Before
     public void setUp() throws Exception {
         sshd = setupTestServer();
@@ -580,7 +586,6 @@ public class PortForwardingTest extends BaseTestSupport {
     }
 
     protected Session createSession() throws JSchException {
-        JSchLogger.init();
         JSch sch = new JSch();
         Session session = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, sshPort);
         session.setUserInfo(new SimpleUserInfo(getCurrentTestName()));

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/14eb57c1/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
index 72237c3..8c561dc 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
@@ -37,6 +37,7 @@ import org.apache.sshd.util.test.JSchLogger;
 import org.apache.sshd.util.test.SimpleUserInfo;
 import org.apache.sshd.util.test.Utils;
 import org.junit.Assume;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -89,6 +90,11 @@ public class CipherTest extends BaseTestSupport {
         return PARAMETERS;
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     private final Random random = Utils.getRandomizerInstance();
     private final BuiltinCiphers builtInCipher;
     private final Class<? extends com.jcraft.jsch.Cipher> jschCipher;
@@ -117,7 +123,6 @@ public class CipherTest extends BaseTestSupport {
     }
 
     private void runJschTest(int port) throws Exception {
-        JSchLogger.init();
         JSch sch = new JSch();
         JSch.setConfig("cipher.s2c", CRYPT_NAMES);
         JSch.setConfig("cipher.c2s", CRYPT_NAMES);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/14eb57c1/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java b/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java
index e9d98bb..7ff81cc 100644
--- a/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java
@@ -31,6 +31,7 @@ import org.apache.sshd.util.test.JSchLogger;
 import org.apache.sshd.util.test.SimpleUserInfo;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -50,6 +51,11 @@ public class SpringConfigTest extends BaseTestSupport {
         super();
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     @Before
     public void setUp() throws Exception {
         Class<?> clazz = getClass();
@@ -69,7 +75,6 @@ public class SpringConfigTest extends BaseTestSupport {
         SshServer server = context.getBean(SshServer.class);
         int port = server.getPort();
 
-        JSchLogger.init();
         JSch sch = new JSch();
         com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
         s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/14eb57c1/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java
----------------------------------------------------------------------
diff --git a/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java b/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java
index 777ea52..07ee4b2 100644
--- a/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java
+++ b/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java
@@ -34,6 +34,7 @@ import org.eclipse.jgit.api.Git;
 import org.eclipse.jgit.transport.CredentialsProvider;
 import org.eclipse.jgit.transport.SshSessionFactory;
 import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -48,6 +49,11 @@ public class GitPackCommandTest extends BaseTestSupport {
         super();
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     @Test
     public void testGitPack() throws Exception {
         Path targetParent = detectTargetFolder().getParent();
@@ -65,7 +71,6 @@ public class GitPackCommandTest extends BaseTestSupport {
                 Utils.deleteRecursive(serverDir);
                 Git.init().setBare(true).setDirectory(serverDir.toFile()).call();
 
-                JSchLogger.init();
                 JSch.setConfig("StrictHostKeyChecking", "no");
                 CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider(getCurrentTestName(), getCurrentTestName()));
                 SshSessionFactory.setInstance(new GitSshdSessionFactory());


[5/7] mina-sshd git commit: Using same test username / password as all the rest of the tests

Posted by lg...@apache.org.
Using same test username / password as all the rest of the tests


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

Branch: refs/heads/master
Commit: 844cd7213c2ba53fcada35aee22f0f4949df5e8a
Parents: 3d57e88
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:37:34 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:37:34 2015 +0200

----------------------------------------------------------------------
 sshd-core/src/test/java/org/apache/sshd/LoadTest.java | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/844cd721/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
index 45c8c4b..a0f09a5 100644
--- a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
@@ -122,8 +122,8 @@ public class LoadTest extends BaseTestSupport {
                     ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
             client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
             client.start();
-            try (ClientSession session = client.connect("sshd", TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
-                session.addPasswordIdentity("sshd");
+            try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
+                session.addPasswordIdentity(getCurrentTestName());
                 session.auth().verify(5L, TimeUnit.SECONDS);
 
                 try (ByteArrayOutputStream out = new ByteArrayOutputStream();


[4/7] mina-sshd git commit: Using a VirtualFileSystemFactory for the test instead of an anonymous FileSystemFactory

Posted by lg...@apache.org.
Using a VirtualFileSystemFactory for the test instead of an anonymous FileSystemFactory

* Related to SSHD-605


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

Branch: refs/heads/master
Commit: 3d57e889df8d54828f4ee9f3767edb38f4124d5e
Parents: 14eb57c
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:37:01 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:37:01 2015 +0200

----------------------------------------------------------------------
 .../org/apache/sshd/client/scp/ScpTest.java     | 93 ++++++++------------
 .../sshd/client/simple/SimpleScpClientTest.java | 12 +--
 .../client/simple/SimpleSftpClientTest.java     | 12 +--
 .../sftp/AbstractSftpClientTestSupport.java     | 13 +--
 .../subsystem/sftp/SftpFileSystemTest.java      | 11 +--
 .../sshd/client/subsystem/sftp/SftpTest.java    | 47 +++++++++-
 6 files changed, 93 insertions(+), 95 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/3d57e889/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
index a5e7197..5c85dec 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
@@ -25,34 +25,25 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import java.nio.channels.FileChannel;
 import java.nio.charset.StandardCharsets;
-import java.nio.file.FileSystem;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.StandardOpenOption;
 import java.nio.file.attribute.PosixFilePermission;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.Date;
 import java.util.EnumSet;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
-import ch.ethz.ssh2.Connection;
-import ch.ethz.ssh2.ConnectionInfo;
-import ch.ethz.ssh2.SCPClient;
-import com.jcraft.jsch.ChannelExec;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
 import org.apache.sshd.client.SshClient;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.Factory;
 import org.apache.sshd.common.file.FileSystemFactory;
-import org.apache.sshd.common.file.root.RootedFileSystemProvider;
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
 import org.apache.sshd.common.random.Random;
 import org.apache.sshd.common.scp.ScpHelper;
 import org.apache.sshd.common.scp.ScpTransferEventListener;
-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.io.IoUtils;
@@ -64,13 +55,21 @@ import org.apache.sshd.util.test.SimpleUserInfo;
 import org.apache.sshd.util.test.Utils;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+
+import ch.ethz.ssh2.Connection;
+import ch.ethz.ssh2.ConnectionInfo;
+import ch.ethz.ssh2.SCPClient;
+
 /**
  * Test for SCP support.
  *
@@ -81,19 +80,17 @@ public class ScpTest extends BaseTestSupport {
 
     private SshServer sshd;
     private int port;
-    private com.jcraft.jsch.Session session;
     private final FileSystemFactory fileSystemFactory;
 
     public ScpTest() throws IOException {
         Path targetPath = detectTargetFolder();
         Path parentPath = targetPath.getParent();
-        final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap());
-        fileSystemFactory = new FileSystemFactory() {
-            @Override
-            public FileSystem createFileSystem(Session session) throws IOException {
-                return fileSystem;
-            }
-        };
+        fileSystemFactory = new VirtualFileSystemFactory(parentPath);
+    }
+
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
     }
 
     @Before
@@ -105,34 +102,14 @@ public class ScpTest extends BaseTestSupport {
         port = sshd.getPort();
     }
 
-    protected com.jcraft.jsch.Session getJschSession() throws JSchException {
-        JSchLogger.init();
-        JSch sch = new JSch();
-        session = sch.getSession("sshd", TEST_LOCALHOST, port);
-        session.setUserInfo(new SimpleUserInfo("sshd"));
-        session.connect();
-        return session;
-    }
-
     @After
     public void tearDown() throws Exception {
-        if (session != null) {
-            session.disconnect();
-        }
-
         if (sshd != null) {
             sshd.stop(true);
         }
     }
 
     @Test
-    @Ignore
-    public void testExternal() throws Exception {
-        System.out.println("Scp available on port " + port);
-        Thread.sleep(5 * 60000);
-    }
-
-    @Test
     public void testNormalizedScpRemotePaths() throws Exception {
         Path targetPath = detectTargetFolder();
         Path parentPath = targetPath.getParent();
@@ -742,7 +719,7 @@ public class ScpTest extends BaseTestSupport {
 
     @Test
     public void testJschScp() throws Exception {
-        session = getJschSession();
+        com.jcraft.jsch.Session session = getJschSession();
         try {
             String data = getCurrentTestName() + "\n";
 
@@ -757,31 +734,39 @@ public class ScpTest extends BaseTestSupport {
 
             target.delete();
             assertFalse(target.exists());
-            sendFile(unixPath, fileName, data);
+            sendFile(session, unixPath, fileName, data);
             assertFileLength(target, data.length(), TimeUnit.SECONDS.toMillis(5L));
 
             target.delete();
             assertFalse(target.exists());
-            sendFile(unixDir, fileName, data);
+            sendFile(session, unixDir, fileName, data);
             assertFileLength(target, data.length(), TimeUnit.SECONDS.toMillis(5L));
 
-            sendFileError("target", ScpHelper.SCP_COMMAND_PREFIX, data);
+            sendFileError(session, "target", ScpHelper.SCP_COMMAND_PREFIX, data);
 
-            readFileError(unixDir);
+            readFileError(session, unixDir);
 
-            assertEquals("Mismatched file data", data, readFile(unixPath, target.length()));
-            assertEquals("Mismatched dir data", data, readDir(unixDir, fileName, target.length()));
+            assertEquals("Mismatched file data", data, readFile(session, unixPath, target.length()));
+            assertEquals("Mismatched dir data", data, readDir(session, unixDir, fileName, target.length()));
 
             target.delete();
             root.delete();
 
-            sendDir("target", ScpHelper.SCP_COMMAND_PREFIX, fileName, data);
+            sendDir(session, "target", ScpHelper.SCP_COMMAND_PREFIX, fileName, data);
             assertFileLength(target, data.length(), TimeUnit.SECONDS.toMillis(5L));
         } finally {
             session.disconnect();
         }
     }
 
+    protected com.jcraft.jsch.Session getJschSession() throws JSchException {
+        JSch sch = new JSch();
+        com.jcraft.jsch.Session session = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
+        session.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
+        session.connect();
+        return session;
+    }
+
     @Test
     public void testWithGanymede() throws Exception {
         Path targetPath = detectTargetFolder();
@@ -800,6 +785,7 @@ public class ScpTest extends BaseTestSupport {
                 PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE
         ));
 
+        ch.ethz.ssh2.log.Logger.enabled = true;
         final Connection conn = new Connection(TEST_LOCALHOST, port);
         try {
             ConnectionInfo info = conn.connect(null, (int) TimeUnit.SECONDS.toMillis(5L), (int) TimeUnit.SECONDS.toMillis(11L));
@@ -832,7 +818,7 @@ public class ScpTest extends BaseTestSupport {
         }
     }
 
-    protected String readFile(String path, long expectedSize) throws Exception {
+    protected String readFile(com.jcraft.jsch.Session session, String path, long expectedSize) throws Exception {
         ChannelExec c = (ChannelExec) session.openChannel("exec");
         c.setCommand("scp -f " + path);
         c.connect();
@@ -865,7 +851,7 @@ public class ScpTest extends BaseTestSupport {
         }
     }
 
-    protected String readDir(String path, String fileName, long expectedSize) throws Exception {
+    protected String readDir(com.jcraft.jsch.Session session, String path, String fileName, long expectedSize) throws Exception {
         ChannelExec c = (ChannelExec) session.openChannel("exec");
         c.setCommand("scp -r -f " + path);
         c.connect();
@@ -905,7 +891,7 @@ public class ScpTest extends BaseTestSupport {
         }
     }
 
-    protected String readFileError(String path) throws Exception {
+    protected void readFileError(com.jcraft.jsch.Session session, String path) throws Exception {
         ChannelExec c = (ChannelExec) session.openChannel("exec");
         String command = "scp -f " + path;
         c.setCommand(command);
@@ -917,13 +903,12 @@ public class ScpTest extends BaseTestSupport {
             os.write(0);
             os.flush();
             assertEquals("Mismatched response for command: " + command, 2, is.read());
-            return null;
         } finally {
             c.disconnect();
         }
     }
 
-    protected void sendFile(String path, String name, String data) throws Exception {
+    protected void sendFile(com.jcraft.jsch.Session session, String path, String name, String data) throws Exception {
         ChannelExec c = (ChannelExec) session.openChannel("exec");
         String command = "scp -t " + path;
         c.setCommand(command);
@@ -958,7 +943,7 @@ public class ScpTest extends BaseTestSupport {
         assertEquals("No ACK for command=" + command, 0, is.read());
     }
 
-    protected void sendFileError(String path, String name, String data) throws Exception {
+    protected void sendFileError(com.jcraft.jsch.Session session, String path, String name, String data) throws Exception {
         ChannelExec c = (ChannelExec) session.openChannel("exec");
         String command = "scp -t " + path;
         c.setCommand(command);
@@ -978,7 +963,7 @@ public class ScpTest extends BaseTestSupport {
         }
     }
 
-    protected void sendDir(String path, String dirName, String fileName, String data) throws Exception {
+    protected void sendDir(com.jcraft.jsch.Session session, String path, String dirName, String fileName, String data) throws Exception {
         ChannelExec c = (ChannelExec) session.openChannel("exec");
         String command = "scp -t -r " + path;
         c.setCommand(command);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/3d57e889/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleScpClientTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleScpClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleScpClientTest.java
index 5fbd1cc..e05c093 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleScpClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleScpClientTest.java
@@ -20,14 +20,12 @@
 package org.apache.sshd.client.simple;
 
 import java.io.IOException;
-import java.nio.file.FileSystem;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.util.Collections;
 
 import org.apache.sshd.client.scp.CloseableScpClient;
 import org.apache.sshd.common.file.FileSystemFactory;
-import org.apache.sshd.common.file.root.RootedFileSystemProvider;
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
 import org.apache.sshd.common.scp.ScpHelper;
 import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.util.io.IoUtils;
@@ -49,13 +47,7 @@ public class SimpleScpClientTest extends BaseSimpleClientTestSupport {
     public SimpleScpClientTest() throws Exception {
         targetPath = detectTargetFolder();
         parentPath = targetPath.getParent();
-        final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap());
-        fileSystemFactory = new FileSystemFactory() {
-            @Override
-            public FileSystem createFileSystem(Session session) throws IOException {
-                return fileSystem;
-            }
-        };
+        fileSystemFactory = new VirtualFileSystemFactory(parentPath);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/3d57e889/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSftpClientTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSftpClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSftpClientTest.java
index 6482442..4fe9a78 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSftpClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSftpClientTest.java
@@ -21,11 +21,9 @@ package org.apache.sshd.client.simple;
 
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
-import java.nio.file.FileSystem;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.EnumSet;
 import java.util.Iterator;
 import java.util.List;
@@ -33,7 +31,7 @@ import java.util.List;
 import org.apache.sshd.client.subsystem.sftp.SftpClient;
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.file.FileSystemFactory;
-import org.apache.sshd.common.file.root.RootedFileSystemProvider;
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
 import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.subsystem.sftp.SftpConstants;
 import org.apache.sshd.common.util.io.IoUtils;
@@ -57,13 +55,7 @@ public class SimpleSftpClientTest extends BaseSimpleClientTestSupport {
     public SimpleSftpClientTest() throws Exception {
         targetPath = detectTargetFolder();
         parentPath = targetPath.getParent();
-        final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap());
-        fileSystemFactory = new FileSystemFactory() {
-            @Override
-            public FileSystem createFileSystem(Session session) throws IOException {
-                return fileSystem;
-            }
-        };
+        fileSystemFactory = new VirtualFileSystemFactory(parentPath);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/3d57e889/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java
index c743cad..b4e9fa9 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java
@@ -20,15 +20,13 @@
 package org.apache.sshd.client.subsystem.sftp;
 
 import java.io.IOException;
-import java.nio.file.FileSystem;
 import java.nio.file.Path;
 import java.util.Collections;
 
 import org.apache.sshd.client.subsystem.sftp.extensions.SftpClientExtension;
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.file.FileSystemFactory;
-import org.apache.sshd.common.file.root.RootedFileSystemProvider;
-import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
 import org.apache.sshd.server.Command;
 import org.apache.sshd.server.SshServer;
 import org.apache.sshd.server.command.ScpCommandFactory;
@@ -41,19 +39,12 @@ import org.apache.sshd.util.test.BaseTestSupport;
 public abstract class AbstractSftpClientTestSupport extends BaseTestSupport {
     protected SshServer sshd;
     protected int port;
-    protected final FileSystem rootFileSystem;
     protected final FileSystemFactory fileSystemFactory;
 
     protected AbstractSftpClientTestSupport() throws IOException {
         Path targetPath = detectTargetFolder();
         Path parentPath = targetPath.getParent();
-        rootFileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap());
-        fileSystemFactory = new FileSystemFactory() {
-            @Override
-            public FileSystem createFileSystem(Session session) throws IOException {
-                return rootFileSystem;
-            }
-        };
+        fileSystemFactory = new VirtualFileSystemFactory(parentPath);
     }
 
     protected void setupServer() throws Exception {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/3d57e889/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java
index cb00f99..64ca4aa 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java
@@ -57,8 +57,7 @@ import org.apache.sshd.client.SshClient;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.file.FileSystemFactory;
-import org.apache.sshd.common.file.root.RootedFileSystemProvider;
-import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
 import org.apache.sshd.common.subsystem.sftp.SftpConstants;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.OsUtils;
@@ -85,13 +84,7 @@ public class SftpFileSystemTest extends BaseTestSupport {
     public SftpFileSystemTest() throws IOException {
         Path targetPath = detectTargetFolder();
         Path parentPath = targetPath.getParent();
-        final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap());
-        fileSystemFactory = new FileSystemFactory() {
-            @Override
-            public FileSystem createFileSystem(Session session) throws IOException {
-                return fileSystem;
-            }
-        };
+        fileSystemFactory = new VirtualFileSystemFactory(parentPath);
     }
 
     @Before

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/3d57e889/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java
index a902e88..3988a64 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java
@@ -59,6 +59,7 @@ import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.OptionalFeature;
 import org.apache.sshd.common.PropertyResolverUtils;
 import org.apache.sshd.common.file.FileSystemFactory;
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
 import org.apache.sshd.common.random.Random;
 import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.subsystem.sftp.SftpConstants;
@@ -90,6 +91,7 @@ import org.apache.sshd.util.test.Utils;
 import org.junit.After;
 import org.junit.Assume;
 import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -111,10 +113,14 @@ public class SftpTest extends AbstractSftpClientTestSupport {
         super();
     }
 
+    @BeforeClass
+    public static void jschInit() {
+        JSchLogger.init();
+    }
+
     @Before
     public void setUp() throws Exception {
         setupServer();
-        JSchLogger.init();
         JSch sch = new JSch();
         session = sch.getSession("sshd", TEST_LOCALHOST, port);
         session.setUserInfo(new SimpleUserInfo("sshd"));
@@ -258,6 +264,45 @@ public class SftpTest extends AbstractSftpClientTestSupport {
         }
     }
 
+    @Test   // see SSHD-605
+    public void testCannotEscapeUserRoot() throws Exception {
+        Path targetPath = detectTargetFolder();
+        Path lclSftp = Utils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName());
+        assertHierarchyTargetFolderExists(lclSftp);
+        sshd.setFileSystemFactory(new VirtualFileSystemFactory(lclSftp));
+
+        try (SshClient client = setupTestClient()) {
+            client.start();
+
+            try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
+                session.addPasswordIdentity(getCurrentTestName());
+                session.auth().verify(5L, TimeUnit.SECONDS);
+
+                String escapePath = targetPath.toString();
+                if (OsUtils.isWin32()) {
+                    escapePath = "/" + escapePath.replace(File.separatorChar, '/');
+                }
+
+                try (SftpClient sftp = session.createSftpClient()) {
+                    SftpClient.Attributes attrs = sftp.stat(escapePath);
+                    fail("Unexpected escape success for path=" + escapePath + ": " + attrs);
+                } catch(SftpException e) {
+                    if (OsUtils.isWin32()) {
+                        assertEquals("Mismatched status for " + escapePath,
+                                     SftpConstants.getStatusName(SftpConstants.SSH_FX_INVALID_FILENAME),
+                                     SftpConstants.getStatusName(e.getStatus()));
+                    } else {
+                        assertEquals("Mismatched status for " + escapePath,
+                                     SftpConstants.getStatusName(SftpConstants.SSH_FX_NO_SUCH_FILE),
+                                     SftpConstants.getStatusName(e.getStatus()));
+                    }
+                }
+            } finally {
+                client.stop();
+            }
+        }
+    }
+
     @Test
     public void testNormalizeRemoteRootValues() throws Exception {
         try (SshClient client = setupTestClient()) {


[2/7] mina-sshd git commit: Added some more detailed log messages

Posted by lg...@apache.org.
Added some more detailed log messages


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

Branch: refs/heads/master
Commit: e5d6d805b946257f8636116208fc305479bce405
Parents: d848718
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:33:01 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:33:01 2015 +0200

----------------------------------------------------------------------
 .../apache/sshd/server/command/ScpCommand.java  |   4 +-
 .../server/subsystem/sftp/SftpSubsystem.java    | 115 ++++++++++---------
 2 files changed, 64 insertions(+), 55 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/e5d6d805/sshd-core/src/main/java/org/apache/sshd/server/command/ScpCommand.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/command/ScpCommand.java b/sshd-core/src/main/java/org/apache/sshd/server/command/ScpCommand.java
index 549a767..7d75f4e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/command/ScpCommand.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/command/ScpCommand.java
@@ -109,7 +109,9 @@ public class ScpCommand extends AbstractLoggingBean implements Command, Runnable
 
         listener = (eventListener == null) ? ScpTransferEventListener.EMPTY : eventListener;
 
-        log.debug("Executing command {}", command);
+        if (log.isDebugEnabled()) {
+            log.debug("Executing command {}", command);
+        }
         String[] args = command.split(" ");
         for (int i = 1; i < args.length; i++) {
             String argVal = args[i];

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/e5d6d805/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java b/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java
index e67804a..13b7472 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystem.java
@@ -73,6 +73,7 @@ import java.util.TreeSet;
 import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.sshd.common.Factory;
 import org.apache.sshd.common.FactoryManager;
@@ -287,7 +288,6 @@ public class SftpSubsystem
     protected Random randomizer;
     protected int fileHandleSize = DEFAULT_FILE_HANDLE_SIZE;
     protected int maxFileHandleRounds = DEFAULT_FILE_HANDLE_ROUNDS;
-    protected boolean closed;
     protected ExecutorService executors;
     protected boolean shutdownExecutor;
     protected Future<?> pendingFuture;
@@ -301,6 +301,7 @@ public class SftpSubsystem
     protected final UnsupportedAttributePolicy unsupportedAttributePolicy;
 
     private ServerSession serverSession;
+    private final AtomicBoolean closed = new AtomicBoolean(false);
     private final Collection<SftpEventListener> sftpEventListeners = new CopyOnWriteArraySet<>();
     private final SftpEventListener sftpEventListenerProxy;
 
@@ -441,8 +442,12 @@ public class SftpSubsystem
                 process(buffer);
             }
         } catch (Throwable t) {
-            if ((!closed) && (!(t instanceof EOFException))) { // Ignore
-                log.error("Exception caught in SFTP subsystem", t);
+            if ((!closed.get()) && (!(t instanceof EOFException))) { // Ignore
+                log.error("run({}) {} caught in SFTP subsystem: {}",
+                          getServerSession(), t.getClass().getSimpleName(), t.getMessage());
+                if (log.isDebugEnabled()) {
+                    log.debug("run(" + getServerSession() + ") caught exception details", t);
+                }
             }
         } finally {
             for (Map.Entry<String, Handle> entry : handles.entrySet()) {
@@ -451,11 +456,12 @@ public class SftpSubsystem
                 try {
                     handle.close();
                     if (log.isDebugEnabled()) {
-                        log.debug("Closed pending handle {} [{}]", id, handle);
+                        log.debug("run({}) closed pending handle {} [{}]",
+                                  getServerSession(), id, handle);
                     }
                 } catch (IOException ioe) {
-                    log.error("Failed ({}) to close handle={}[{}]: {}",
-                              ioe.getClass().getSimpleName(), id, handle, ioe.getMessage());
+                    log.error("run({}) failed ({}) to close handle={}[{}]: {}",
+                              getServerSession(), ioe.getClass().getSimpleName(), id, handle, ioe.getMessage());
                 }
             }
 
@@ -1555,13 +1561,14 @@ public class SftpSubsystem
                             attrs = getAttributes(p, IoUtils.getLinkOptions(false));
                         } catch (IOException e) {
                             if (log.isDebugEnabled()) {
-                                log.debug("Failed ({}) to retrieve attributes of {}: {}",
-                                        e.getClass().getSimpleName(), p, e.getMessage());
+                                log.debug("doRealPath({}) - failed ({}) to retrieve attributes of {}: {}",
+                                          getServerSession(), e.getClass().getSimpleName(), p, e.getMessage());
                             }
                         }
                     } else {
                         if (log.isDebugEnabled()) {
-                            log.debug("Dummy attributes for non-existing file: " + p);
+                            log.debug("doRealPath({}) - dummy attributes for non-existing file: {}",
+                                      getServerSession(), p);
                         }
                     }
                 } else if (control == SftpConstants.SSH_FXP_REALPATH_STAT_ALWAYS) {
@@ -2880,14 +2887,13 @@ public class SftpSubsystem
                 attrs.put(name, resolved);
 
                 if (log.isDebugEnabled()) {
-                    log.debug("resolveMissingFileAttributes(" + file + ")[" + name + "]"
-                            + " replace " + value + " with " + resolved);
+                    log.debug("resolveMissingFileAttributes({})[{}[{}]] replace {} with {}",
+                              getServerSession(), file, name, value, resolved);
                 }
             } catch (IOException e) {
                 if (log.isDebugEnabled()) {
-                    log.debug("resolveMissingFileAttributes(" + file + ")[" + name + "]"
-                            + " failed (" + e.getClass().getSimpleName() + ")"
-                            + " to resolve missing value: " + e.getMessage());
+                    log.debug("resolveMissingFileAttributes({})[{}[{}]] failed ({}) to resolve missing value: {}",
+                              getServerSession(), file, name, e.getClass().getSimpleName(), e.getMessage());
                 }
             }
         }
@@ -3312,56 +3318,57 @@ public class SftpSubsystem
 
     @Override
     public void destroy() {
-        if (!closed) {
-            if (log.isDebugEnabled()) {
-                log.debug("destroy({}) - mark as closed", getServerSession());
-            }
+        if (closed.getAndSet(true)) {
+            return; // ignore if already closed
+        }
 
-            closed = true;
+        ServerSession session = getServerSession();
+        if (log.isDebugEnabled()) {
+            log.debug("destroy({}) - mark as closed", session);
+        }
 
-            try {
-                SftpEventListener listener = getSftpEventListenerProxy();
-                listener.destroying(getServerSession());
-            } catch (Exception e) {
-                log.warn("destroy({}) Failed ({}) to announce destruction event: {}",
-                         getServerSession(), e.getClass().getSimpleName(), e.getMessage());
-                if (log.isDebugEnabled()) {
-                    log.debug("destroy(" + getServerSession() + ") destruction announcement failure details", e);
-                }
+        try {
+            SftpEventListener listener = getSftpEventListenerProxy();
+            listener.destroying(session);
+        } catch (Exception e) {
+            log.warn("destroy({}) Failed ({}) to announce destruction event: {}",
+                    session, e.getClass().getSimpleName(), e.getMessage());
+            if (log.isDebugEnabled()) {
+                log.debug("destroy(" + session + ") destruction announcement failure details", e);
             }
+        }
 
-            // if thread has not completed, cancel it
-            if ((pendingFuture != null) && (!pendingFuture.isDone())) {
-                boolean result = pendingFuture.cancel(true);
-                // TODO consider waiting some reasonable (?) amount of time for cancellation
-                if (log.isDebugEnabled()) {
-                    log.debug("destroy(" + getServerSession() + ") - cancel pending future=" + result);
-                }
+        // if thread has not completed, cancel it
+        if ((pendingFuture != null) && (!pendingFuture.isDone())) {
+            boolean result = pendingFuture.cancel(true);
+            // TODO consider waiting some reasonable (?) amount of time for cancellation
+            if (log.isDebugEnabled()) {
+                log.debug("destroy(" + session + ") - cancel pending future=" + result);
             }
+        }
 
-            pendingFuture = null;
+        pendingFuture = null;
 
-            if ((executors != null) && (!executors.isShutdown()) && shutdownExecutor) {
-                Collection<Runnable> runners = executors.shutdownNow();
-                if (log.isDebugEnabled()) {
-                    log.debug("destroy(" + getServerSession() + ") - shutdown executor service - runners count=" + runners.size());
-                }
+        if ((executors != null) && (!executors.isShutdown()) && shutdownExecutor) {
+            Collection<Runnable> runners = executors.shutdownNow();
+            if (log.isDebugEnabled()) {
+                log.debug("destroy(" + session + ") - shutdown executor service - runners count=" + runners.size());
             }
+        }
 
-            executors = null;
+        executors = null;
 
-            try {
-                fileSystem.close();
-            } catch (UnsupportedOperationException e) {
-                if (log.isDebugEnabled()) {
-                    log.debug("destroy(" + getServerSession() + ") closing the file system is not supported");
-                }
-            } catch (IOException e) {
-                if (log.isDebugEnabled()) {
-                    log.debug("destroy(" + getServerSession() + ")"
-                            + " failed (" + e.getClass().getSimpleName() + ")"
-                            + " to close file system: " + e.getMessage(), e);
-                }
+        try {
+            fileSystem.close();
+        } catch (UnsupportedOperationException e) {
+            if (log.isDebugEnabled()) {
+                log.debug("destroy(" + session + ") closing the file system is not supported");
+            }
+        } catch (IOException e) {
+            if (log.isDebugEnabled()) {
+                log.debug("destroy(" + session + ")"
+                        + " failed (" + e.getClass().getSimpleName() + ")"
+                        + " to close file system: " + e.getMessage(), e);
             }
         }
     }


[7/7] mina-sshd git commit: Enable Ganymed logger for MacTest(s)

Posted by lg...@apache.org.
Enable Ganymed logger for MacTest(s)


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

Branch: refs/heads/master
Commit: 799f1cca499fb41d73bd18aeaca6e9f8518626a6
Parents: 089624a
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Thu Dec 3 08:38:35 2015 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Thu Dec 3 08:38:35 2015 +0200

----------------------------------------------------------------------
 sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/799f1cca/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java b/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java
index b749e9a..68b0d79 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java
@@ -176,6 +176,7 @@ public class MacTest extends BaseTestSupport {
         String macName = factory.getName();
         Assume.assumeTrue("Factory not supported: " + macName, ganymedMacs.contains(macName));
 
+        ch.ethz.ssh2.log.Logger.enabled = true;
         Connection conn = new Connection(TEST_LOCALHOST, port);
         try {
             conn.setClient2ServerMACs(new String[]{macName});