From fad1582b22fdad3eedc1c0325764fd3eeb168afb Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 13 Mar 2023 07:26:45 -0500 Subject: [PATCH 01/11] Update to latest Maven Wrapper. --- .mvn/wrapper/MavenWrapperDownloader.java | 162 --------- .mvn/wrapper/maven-wrapper.properties | 4 +- mvnw | 414 ++++++++++------------- mvnw.cmd | 282 +++++++-------- 4 files changed, 305 insertions(+), 557 deletions(-) delete mode 100644 .mvn/wrapper/MavenWrapperDownloader.java diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index 732313c4..00000000 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.IOException; -import java.io.InputStream; -import java.net.Authenticator; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.util.Properties; - -public final class MavenWrapperDownloader -{ - private static final String WRAPPER_VERSION = "3.1.1"; - - private static final boolean VERBOSE = Boolean.parseBoolean( System.getenv( "MVNW_VERBOSE" ) ); - - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = - "https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/" + WRAPPER_VERSION - + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use instead of the - * default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main( String[] args ) - { - if ( args.length == 0 ) - { - System.err.println( " - ERROR projectBasedir parameter missing" ); - System.exit( 1 ); - } - - log( " - Downloader started" ); - final String dir = args[0].replace( "..", "" ); // Sanitize path - final Path projectBasedir = Paths.get( dir ).toAbsolutePath().normalize(); - if ( !Files.isDirectory( projectBasedir, LinkOption.NOFOLLOW_LINKS ) ) - { - System.err.println( " - ERROR projectBasedir not exists: " + projectBasedir ); - System.exit( 1 ); - } - - log( " - Using base directory: " + projectBasedir ); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - Path mavenWrapperPropertyFile = projectBasedir.resolve( MAVEN_WRAPPER_PROPERTIES_PATH ); - String url = readWrapperUrl( mavenWrapperPropertyFile ); - - try - { - Path outputFile = projectBasedir.resolve( MAVEN_WRAPPER_JAR_PATH ); - createDirectories( outputFile.getParent() ); - downloadFileFromURL( url, outputFile ); - log( "Done" ); - System.exit( 0 ); - } - catch ( IOException e ) - { - System.err.println( "- Error downloading" ); - e.printStackTrace(); - System.exit( 1 ); - } - } - - private static void downloadFileFromURL( String urlString, Path destination ) throws IOException - { - log( " - Downloading to: " + destination ); - if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null ) - { - final String username = System.getenv( "MVNW_USERNAME" ); - final char[] password = System.getenv( "MVNW_PASSWORD" ).toCharArray(); - Authenticator.setDefault( new Authenticator() - { - @Override - protected PasswordAuthentication getPasswordAuthentication() - { - return new PasswordAuthentication( username, password ); - } - } ); - } - URL website = new URL( urlString ); - try ( InputStream inStream = website.openStream() ) { - Files.copy( inStream, destination, StandardCopyOption.REPLACE_EXISTING ); - } - log( " - Downloader complete" ); - } - - private static void createDirectories(Path outputPath) throws IOException - { - if ( !Files.isDirectory( outputPath, LinkOption.NOFOLLOW_LINKS ) ) { - Path createDirectories = Files.createDirectories( outputPath ); - log( " - Directories created: " + createDirectories ); - } - } - - private static String readWrapperUrl( Path mavenWrapperPropertyFile ) - { - String url = DEFAULT_DOWNLOAD_URL; - if ( Files.exists( mavenWrapperPropertyFile, LinkOption.NOFOLLOW_LINKS ) ) - { - log( " - Reading property file: " + mavenWrapperPropertyFile ); - try ( InputStream in = Files.newInputStream( mavenWrapperPropertyFile, StandardOpenOption.READ ) ) - { - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load( in ); - url = mavenWrapperProperties.getProperty( PROPERTY_NAME_WRAPPER_URL, DEFAULT_DOWNLOAD_URL ); - } - catch ( IOException e ) - { - System.err.println( " - ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'" ); - } - } - log( " - Downloading from: " + url ); - return url; - } - - private static void log( String msg ) - { - if ( VERBOSE ) - { - System.out.println( msg ); - } - } - -} diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 6686a643..08ea486a 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -6,7 +6,7 @@ # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 @@ -15,4 +15,4 @@ # specific language governing permissions and limitations # under the License. distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.0/apache-maven-3.9.0-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/mvnw b/mvnw index b7f06462..633bbb74 100755 --- a/mvnw +++ b/mvnw @@ -19,269 +19,221 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.1.1 -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir +# Apache Maven Wrapper startup batch script, version 3.2.0 # # Optional ENV vars # ----------------- -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output # ---------------------------------------------------------------------------- -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /usr/local/etc/mavenrc ] ; then - . /usr/local/etc/mavenrc - fi - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - JAVA_HOME="`/usr/libexec/java_home`"; export JAVA_HOME - else - JAVA_HOME="/Library/Java/Home"; export JAVA_HOME - fi - fi - ;; +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +(CYGWIN*|MINGW*) [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } ;; esac -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" else JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ] ; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi fi else - JAVACMD="`\\unset -f command; \\command -v java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi + JAVACMD="$('set' +e; 'unset' -f command 2>/dev/null; 'command' -v java)" || : + JAVACCMD="$('set' +e; 'unset' -f command 2>/dev/null; 'command' -v javac)" || : -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ] ; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi fi +} - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + h=$(( ( h * 31 + $(LC_CTYPE=C printf %d "'$str") ) % 4294967296 )) + str="${str#?}" done - printf '%s' "$(cd "$basedir"; pwd)" + printf %x\\n $h } -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 } -BASE_DIR=$(find_maven_basedir "$(dirname $0)") -if [ -z "$BASE_DIR" ]; then - exit 1; -fi +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl="${value-}" ;; + distributionSha256Sum) distributionSha256Sum="${value-}" ;; + esac +done < "${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + + +case "${distributionUrl##*/}" in +(maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + (*AMD64:CYGWIN*|*AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + (:Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + (:Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + (:Linux*x86_64*) distributionPlatform=linux-amd64 ;; + (*) echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +(maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +(*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac -MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_HOME="$HOME/.m2/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" fi -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi +case "${distributionUrl-}" in +(*?-bin.zip|*?maven-mvnd-?*-?*.zip) ;; +(*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" - else - wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) wrapperUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $wrapperUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi + die "cannot create temp dir" +fi - if command -v wget > /dev/null; then - QUIET="--quiet" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - QUIET="" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" - else - wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" - fi - [ $? -eq 0 ] || rm -f "$wrapperJarPath" - elif command -v curl > /dev/null; then - QUIET="--silent" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - QUIET="" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L - else - curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L - fi - [ $? -eq 0 ] || rm -f "$wrapperJarPath" - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaSource="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaSource=`cygpath --path --windows "$javaSource"` - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaSource" ]; then - if [ ! -e "$javaClass" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaSource") - fi - if [ -e "$javaClass" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" fi -########################################################################################## -# End of extension -########################################################################################## -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +if [ -z "${MVNW_USERNAME-}" ] && command -v wget > /dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl > /dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat > "$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( new java.net.URL( args[0] ).openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" fi -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum > /dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c > /dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c > /dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain +# unzip and move +if command -v unzip > /dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" +fi +printf %s\\n "$distributionUrl" > "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" -exec "$JAVACMD" \ - $MAVEN_OPTS \ - $MAVEN_DEBUG_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd index cba1f040..dd02e16f 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,3 +1,4 @@ +<# : batch portion @REM ---------------------------------------------------------------------------- @REM Licensed to the Apache Software Foundation (ASF) under one @REM or more contributor license agreements. See the NOTICE file @@ -18,170 +19,127 @@ @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.1.1 -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir +@REM Apache Maven Wrapper startup batch script, version 3.2.0 @REM @REM Optional ENV vars -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output @REM ---------------------------------------------------------------------------- -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* -if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" - -FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %WRAPPER_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) ) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% ^ - %JVM_CONFIG_MAVEN_PROPS% ^ - %MAVEN_OPTS% ^ - %MAVEN_DEBUG_OPTS% ^ - -classpath %WRAPPER_JAR% ^ - "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ - %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" -if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%"=="on" pause - -if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% - -cmd /C exit /B %ERROR_CODE% +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" From 3aeecba8ac391476e68f2dc7acc6f01917da4918 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 13 Mar 2023 07:36:13 -0500 Subject: [PATCH 02/11] #287 add algorithm type information to algorithm negotiation logs. --- ChangeLog.md | 2 ++ src/main/java/com/jcraft/jsch/KeyExchange.java | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 245b5387..6ee45453 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,3 +1,5 @@ +* [0.2.8](https://github.com/mwiede/jsch/releases/tag/jsch-0.2.8) + * [#287](https://github.com/mwiede/jsch/issues/287) add algorithm type information to algorithm negotiation logs. * [0.2.7](https://github.com/mwiede/jsch/releases/tag/jsch-0.2.7) * Fix exception logging in Log4j2Logger. * [#265](https://github.com/mwiede/jsch/issues/265) change buffer_margin computation to be dynamic based upon the MAC to allow connections that advertise small maximum packet sizes. diff --git a/src/main/java/com/jcraft/jsch/KeyExchange.java b/src/main/java/com/jcraft/jsch/KeyExchange.java index f227d663..673dcfbd 100644 --- a/src/main/java/com/jcraft/jsch/KeyExchange.java +++ b/src/main/java/com/jcraft/jsch/KeyExchange.java @@ -39,6 +39,9 @@ public abstract class KeyExchange { static final int PROPOSAL_LANG_CTOS = 8; static final int PROPOSAL_LANG_STOC = 9; static final int PROPOSAL_MAX = 10; + static final String[] PROPOSAL_NAMES = + {"KEX algorithms", "host key algorithms", "ciphers c2s", "ciphers s2c", "MACs c2s", + "MACs s2c", "compression c2s", "compression s2c", "languages c2s", "languages s2c"}; // static String kex_algs="diffie-hellman-group-exchange-sha1"+ // ",diffie-hellman-group1-sha1"; @@ -106,10 +109,12 @@ protected static String[] guess(Session session, byte[] I_S, byte[] I_C) throws if (session.getLogger().isEnabled(Logger.INFO)) { for (int i = 0; i < PROPOSAL_MAX; i++) { - session.getLogger().log(Logger.INFO, "kex: server: " + Util.byte2str(sb.getString())); + session.getLogger().log(Logger.INFO, + "server proposal: " + PROPOSAL_NAMES[i] + ": " + Util.byte2str(sb.getString())); } for (int i = 0; i < PROPOSAL_MAX; i++) { - session.getLogger().log(Logger.INFO, "kex: client: " + Util.byte2str(cb.getString())); + session.getLogger().log(Logger.INFO, + "client proposal: " + PROPOSAL_NAMES[i] + ": " + Util.byte2str(cb.getString())); } sb.setOffSet(17); cb.setOffSet(17); From ede6b78842ba3a3a6e5e728e86350f6eb4f4b4b9 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 13 Mar 2023 07:54:00 -0500 Subject: [PATCH 03/11] #289 wrap NoClassDefFoundError's for invalid private keys. --- ChangeLog.md | 1 + src/main/java/com/jcraft/jsch/KeyPair.java | 12 ++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 6ee45453..daa2e1d6 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,5 +1,6 @@ * [0.2.8](https://github.com/mwiede/jsch/releases/tag/jsch-0.2.8) * [#287](https://github.com/mwiede/jsch/issues/287) add algorithm type information to algorithm negotiation logs. + * [#289](https://github.com/mwiede/jsch/issues/289) wrap NoClassDefFoundError's for invalid private keys. * [0.2.7](https://github.com/mwiede/jsch/releases/tag/jsch-0.2.7) * Fix exception logging in Log4j2Logger. * [#265](https://github.com/mwiede/jsch/issues/265) change buffer_margin computation to be dynamic based upon the MAC to allow connections that advertise small maximum packet sizes. diff --git a/src/main/java/com/jcraft/jsch/KeyPair.java b/src/main/java/com/jcraft/jsch/KeyPair.java index 5f3fd1ff..f6826bec 100644 --- a/src/main/java/com/jcraft/jsch/KeyPair.java +++ b/src/main/java/com/jcraft/jsch/KeyPair.java @@ -1119,7 +1119,7 @@ public static KeyPair load(JSch jsch, byte[] prvkey, byte[] pubkey) throws JSchE } return kpair; - } catch (Exception e) { + } catch (Exception | NoClassDefFoundError e) { Util.bzero(data); if (e instanceof JSchException) throw (JSchException) e; @@ -1170,7 +1170,7 @@ static KeyPair loadOpenSSHKeyv1(JSch jsch, byte[] data) throws JSchException { Class.forName(JSch.getConfig(cipherName)).asSubclass(Cipher.class); kpair.cipher = c.getDeclaredConstructor().newInstance(); kpair.iv = new byte[kpair.cipher.getIVSize()]; - } catch (Exception e) { + } catch (Exception | NoClassDefFoundError e) { throw new JSchException("cipher " + cipherName + " is not available", e); } } else { @@ -1186,7 +1186,7 @@ static KeyPair loadOpenSSHKeyv1(JSch jsch, byte[] data) throws JSchException { BCrypt bcrypt = c.getDeclaredConstructor().newInstance(); bcrypt.init(salt, rounds); kpair.kdf = bcrypt; - } catch (Exception e) { + } catch (Exception | NoClassDefFoundError e) { throw new JSchException("kdf " + kdfName + " is not available", e); } } @@ -1285,7 +1285,7 @@ static KeyPair loadPPK(JSch jsch, byte[] buf) throws JSchException { Class.forName(JSch.getConfig("aes256-cbc")).asSubclass(Cipher.class); kpair.cipher = c.getDeclaredConstructor().newInstance(); kpair.iv = new byte[kpair.cipher.getIVSize()]; - } catch (Exception e) { + } catch (Exception | NoClassDefFoundError e) { throw new JSchException("The cipher 'aes256-cbc' is required, but it is not available.", e); } @@ -1299,7 +1299,7 @@ static KeyPair loadPPK(JSch jsch, byte[] buf) throws JSchException { HASH sha1 = c.getDeclaredConstructor().newInstance(); sha1.init(); kpair.sha1 = sha1; - } catch (Exception e) { + } catch (Exception | NoClassDefFoundError e) { throw new JSchException("'sha-1' is required, but it is not available.", e); } } else { @@ -1344,7 +1344,7 @@ static KeyPair loadPPK(JSch jsch, byte[] buf) throws JSchException { kpair.kdf = argon2; } catch (NumberFormatException e) { throw new JSchException("Invalid argon2 params.", e); - } catch (Exception e) { + } catch (Exception | NoClassDefFoundError e) { throw new JSchException("'argon2' is required, but it is not available.", e); } } From 3cbcab3c61f4345dff65b90250b3ffebdcde4bc3 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 13 Mar 2023 09:30:28 -0500 Subject: [PATCH 04/11] Fix compiler warnings in examples. --- examples/AES.java | 9 ++- examples/ChangePassphrase.java | 16 ++-- examples/Compression.java | 12 ++- examples/Daemon.java | 12 ++- examples/Exec.java | 34 +++++---- examples/JSchWithAgentProxy.java | 1 + examples/JumpHosts.java | 16 +++- examples/KeyGen.java | 13 ++-- examples/KnownHosts.java | 19 ++--- examples/Logger.java | 26 +++++-- examples/OpenSSHConfig.java | 43 ++++++----- examples/PortForwardingL.java | 16 ++-- examples/PortForwardingR.java | 18 +++-- examples/ScpFrom.java | 61 ++++++++------- examples/ScpTo.java | 72 +++++++++--------- examples/ScpToNoneCipher.java | 58 ++++++++------ examples/Sftp.java | 126 ++++++++++++++----------------- examples/Shell.java | 41 +++++----- examples/SocketForwardingL.java | 22 +++--- examples/StreamForwarding.java | 14 +++- examples/Subsystem.java | 42 ++++++++--- examples/Sudo.java | 11 ++- examples/UserAuthKI.java | 27 ++++--- examples/UserAuthPubKey.java | 16 ++-- examples/ViaHTTP.java | 14 +++- examples/ViaSOCKS5.java | 14 +++- examples/X11Forwarding.java | 14 +++- 27 files changed, 438 insertions(+), 329 deletions(-) diff --git a/examples/AES.java b/examples/AES.java index e2c57ce9..69e43b87 100644 --- a/examples/AES.java +++ b/examples/AES.java @@ -49,10 +49,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -61,16 +63,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -82,6 +87,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -90,6 +96,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/ChangePassphrase.java b/examples/ChangePassphrase.java index a64b23db..f720b3b5 100644 --- a/examples/ChangePassphrase.java +++ b/examples/ChangePassphrase.java @@ -1,15 +1,14 @@ /** * This program will demonstrate to change the passphrase for a private key file instead of creating - * a new private key. $ CLASSPATH=.:../build javac ChangePassphrase.java $ CLASSPATH=.:../build java - * ChangePassphrase private-key A passphrase will be prompted if the given private-key has been - * encrypted. After successfully loading the content of the private-key, the new passphrase will be - * prompted and the given private-key will be re-encrypted with that new passphrase. + * a new private key. A passphrase will be prompted if the given private-key has been encrypted. + * After successfully loading the content of the private-key, the new passphrase will be prompted + * and the given private-key will be re-encrypted with that new passphrase. * */ import com.jcraft.jsch.*; import javax.swing.*; -class ChangePassphrase { +public class ChangePassphrase { public static void main(String[] arg) { if (arg.length != 1) { System.err.println("usage: java ChangePassphrase private_key"); @@ -28,7 +27,7 @@ public static void main(String[] arg) { String passphrase = ""; while (kpair.isEncrypted()) { - JTextField passphraseField = (JTextField) new JPasswordField(20); + JTextField passphraseField = new JPasswordField(20); Object[] ob = {passphraseField}; int result = JOptionPane.showConfirmDialog(null, ob, "Enter passphrase for " + pkey, JOptionPane.OK_CANCEL_OPTION); @@ -45,7 +44,7 @@ public static void main(String[] arg) { passphrase = ""; - JTextField passphraseField = (JTextField) new JPasswordField(20); + JTextField passphraseField = new JPasswordField(20); Object[] ob = {passphraseField}; int result = JOptionPane.showConfirmDialog(null, ob, "Enter new passphrase for " + pkey + " (empty for no passphrase)", @@ -55,8 +54,7 @@ public static void main(String[] arg) { } passphrase = passphraseField.getText(); - kpair.setPassphrase(passphrase); - kpair.writePrivateKey(pkey); + kpair.writePrivateKey(pkey, passphrase.getBytes()); kpair.dispose(); } catch (Exception e) { System.out.println(e); diff --git a/examples/Compression.java b/examples/Compression.java index c283c2af..d11a6853 100644 --- a/examples/Compression.java +++ b/examples/Compression.java @@ -1,6 +1,5 @@ /** - * This program will demonstrate the packet compression. $ CLASSPATH=.:../build javac - * Compression.java $ CLASSPATH=.:../build java Compression You will be asked username, hostname and + * This program will demonstrate the packet compression. You will be asked username, hostname and * passwd. If everything works fine, you will get the shell prompt. In this program, all data from * sshd server to jsch will be compressed. * @@ -49,10 +48,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -61,16 +62,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -82,6 +86,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -90,6 +95,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/Daemon.java b/examples/Daemon.java index b47f38b9..49de1f6a 100644 --- a/examples/Daemon.java +++ b/examples/Daemon.java @@ -51,16 +51,19 @@ public static class Parrot implements ForwardedTCPIPDaemon { InputStream in; OutputStream out; + @Override public void setChannel(ChannelForwardedTCPIP c, InputStream in, OutputStream out) { this.channel = c; this.in = in; this.out = out; } + @Override public void setArg(Object[] arg) { this.arg = arg; } + @Override public void run() { try { byte[] buf = new byte[1024]; @@ -83,10 +86,12 @@ public void run() { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -95,16 +100,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -116,6 +124,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -124,6 +133,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/Exec.java b/examples/Exec.java index 7822c200..c2c0401b 100644 --- a/examples/Exec.java +++ b/examples/Exec.java @@ -1,8 +1,7 @@ /** - * This program will demonstrate remote exec. $ CLASSPATH=.:../build javac Exec.java $ - * CLASSPATH=.:../build java Exec You will be asked username, hostname, displayname, passwd and - * command. If everything works fine, given command will be invoked on the remote side and outputs - * will be printed out. + * This program will demonstrate remote exec. You will be asked username, hostname, displayname, + * passwd and command. If everything works fine, given command will be invoked on the remote side + * and outputs will be printed out. * */ import com.jcraft.jsch.*; @@ -27,13 +26,13 @@ public static void main(String[] arg) { Session session = jsch.getSession(user, host, 22); - /* - * String xhost="127.0.0.1"; int xport=0; String - * display=JOptionPane.showInputDialog("Enter display name", xhost+":"+xport); - * xhost=display.substring(0, display.indexOf(':')); - * xport=Integer.parseInt(display.substring(display.indexOf(':')+1)); - * session.setX11Host(xhost); session.setX11Port(xport+6000); - */ + // String xhost = "127.0.0.1"; + // int xport = 0; + // String display = JOptionPane.showInputDialog("Enter display name", xhost + ":" + xport); + // xhost = display.substring(0, display.indexOf(':')); + // xport = Integer.parseInt(display.substring(display.indexOf(':') + 1)); + // session.setX11Host(xhost); + // session.setX11Port(xport + 6000); // username and password will be given via UserInfo interface. UserInfo ui = new MyUserInfo(); @@ -53,8 +52,8 @@ public static void main(String[] arg) { // channel.setOutputStream(System.out); - // FileOutputStream fos=new FileOutputStream("/tmp/stderr"); - // ((ChannelExec)channel).setErrStream(fos); + // OutputStream fos = new FileOutputStream("/tmp/stderr"); + // ((ChannelExec) channel).setErrStream(fos); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); @@ -88,10 +87,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -100,16 +101,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -121,6 +125,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -129,6 +134,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/JSchWithAgentProxy.java b/examples/JSchWithAgentProxy.java index 3115bfc3..deb4cc8a 100644 --- a/examples/JSchWithAgentProxy.java +++ b/examples/JSchWithAgentProxy.java @@ -8,6 +8,7 @@ public static void main(String[] arg) { try { JSch jsch = new JSch(); + // IdentityRepository irepo = new AgentIdentityRepository(new PageantConnector()); IdentityRepository irepo = new AgentIdentityRepository(new SSHAgentConnector()); jsch.setIdentityRepository(irepo); diff --git a/examples/JumpHosts.java b/examples/JumpHosts.java index cc2585eb..bdfcb907 100644 --- a/examples/JumpHosts.java +++ b/examples/JumpHosts.java @@ -1,8 +1,8 @@ /** * This program will demonstrate SSH through jump hosts. Suppose that you don't have direct accesses - * to host2 and host3. $ CLASSPATH=.:../build javac JumpHosts.java $ CLASSPATH=.:../build java - * JumpHosts usr1@host1 usr2@host2 usr3@host3 You will be asked passwords for those destinations, - * and if everything works fine, you will get file lists of your home-directory at host3. + * to host2 and host3. java JumpHosts usr1@host1 usr2@host2 usr3@host3. You will be asked passwords + * for those destinations. If everything works fine, you will get file lists of your home-directory + * at host3. * */ import com.jcraft.jsch.*; @@ -52,6 +52,7 @@ public static void main(String[] arg) { sftp.connect(); sftp.ls(".", new ChannelSftp.LsEntrySelector() { + @Override public int select(ChannelSftp.LsEntry le) { System.out.println(le); return ChannelSftp.LsEntrySelector.CONTINUE; @@ -68,10 +69,12 @@ public int select(ChannelSftp.LsEntry le) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -80,16 +83,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -101,6 +107,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -109,6 +116,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/KeyGen.java b/examples/KeyGen.java index 5b220d5f..bb91e4f4 100644 --- a/examples/KeyGen.java +++ b/examples/KeyGen.java @@ -1,15 +1,13 @@ /** - * This progam will demonstrate the DSA keypair generation. $ CLASSPATH=.:../build javac KeyGen.java - * $ CLASSPATH=.:../build java KeyGen rsa output_keyfile comment or $ CLASSPATH=.:../build java - * KeyGen dsa output_keyfile comment You will be asked a passphrase for output_keyfile. If - * everything works fine, you will get the DSA or RSA keypair, output_keyfile and + * This progam will demonstrate the keypair generation. You will be asked a passphrase for + * output_keyfile. If everything works fine, you will get the keypair, output_keyfile and * output_keyfile+".pub". The private key and public key are in the OpenSSH format. * */ import com.jcraft.jsch.*; import javax.swing.*; -class KeyGen { +public class KeyGen { public static void main(String[] arg) { int key_size = 1024; if (arg.length < 3) { @@ -49,7 +47,7 @@ public static void main(String[] arg) { JSch jsch = new JSch(); String passphrase = ""; - JTextField passphraseField = (JTextField) new JPasswordField(20); + JTextField passphraseField = new JPasswordField(20); Object[] ob = {passphraseField}; int result = JOptionPane.showConfirmDialog(null, ob, "Enter passphrase (empty for no passphrase)", JOptionPane.OK_CANCEL_OPTION); @@ -59,8 +57,7 @@ public static void main(String[] arg) { try { KeyPair kpair = KeyPair.genKeyPair(jsch, type, key_size); - kpair.setPassphrase(passphrase); - kpair.writePrivateKey(filename); + kpair.writePrivateKey(filename, passphrase.getBytes()); kpair.writePublicKey(filename + ".pub", comment); System.out.println("Finger print: " + kpair.getFingerPrint()); kpair.dispose(); diff --git a/examples/KnownHosts.java b/examples/KnownHosts.java index 5a85ccb5..f3eeea81 100644 --- a/examples/KnownHosts.java +++ b/examples/KnownHosts.java @@ -1,8 +1,8 @@ /** - * This program will demonstrate the 'known_hosts' file handling. $ CLASSPATH=.:../build javac - * KnownHosts.java $ CLASSPATH=.:../build java KnownHosts You will be asked username, hostname, a - * path for 'known_hosts' and passwd. If everything works fine, you will get the shell prompt. In - * current implementation, jsch only reads 'known_hosts' for checking and does not modify it. + * This program will demonstrate the 'known_hosts' file handling. You will be asked username, + * hostname, a path for 'known_hosts' and passwd. If everything works fine, you will get the shell + * prompt. In current implementation, jsch only reads 'known_hosts' for checking and does not modify + * it. * */ import com.jcraft.jsch.*; @@ -28,8 +28,7 @@ public static void main(String[] arg) { HostKey[] hks = hkr.getHostKey(); if (hks != null) { System.out.println("Host keys in " + hkr.getKnownHostsRepositoryID()); - for (int i = 0; i < hks.length; i++) { - HostKey hk = hks[i]; + for (HostKey hk : hks) { System.out.println(hk.getHost() + " " + hk.getType() + " " + hk.getFingerPrint(jsch)); } System.out.println(""); @@ -51,10 +50,8 @@ public static void main(String[] arg) { UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); - /* - * // In adding to known_hosts file, host names will be hashed. - * session.setConfig("HashKnownHosts", "yes"); - */ + // In adding to known_hosts file, host names will be hashed. + // session.setConfig("HashKnownHosts", "yes"); session.connect(); @@ -88,7 +85,7 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); public String getPassphrase() { return null; diff --git a/examples/Logger.java b/examples/Logger.java index b1bd37db..4f76617b 100644 --- a/examples/Logger.java +++ b/examples/Logger.java @@ -1,5 +1,6 @@ /** * This program will demonstrate how to enable logging mechanism and get logging messages. + * */ import com.jcraft.jsch.*; import java.awt.*; @@ -42,30 +43,34 @@ public static void main(String[] arg) { } public static class MyLogger implements com.jcraft.jsch.Logger { - static java.util.Hashtable name = new java.util.Hashtable(); + static java.util.Map name = new java.util.HashMap<>(); static { - name.put(new Integer(DEBUG), "DEBUG: "); - name.put(new Integer(INFO), "INFO: "); - name.put(new Integer(WARN), "WARN: "); - name.put(new Integer(ERROR), "ERROR: "); - name.put(new Integer(FATAL), "FATAL: "); + name.put(DEBUG, "DEBUG: "); + name.put(INFO, "INFO: "); + name.put(WARN, "WARN: "); + name.put(ERROR, "ERROR: "); + name.put(FATAL, "FATAL: "); } + @Override public boolean isEnabled(int level) { return true; } + @Override public void log(int level, String message) { - System.err.print(name.get(new Integer(level))); + System.err.print(name.get(level)); System.err.println(message); } } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -74,16 +79,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -95,6 +103,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -103,6 +112,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/OpenSSHConfig.java b/examples/OpenSSHConfig.java index 4be2fc67..f7dd22de 100644 --- a/examples/OpenSSHConfig.java +++ b/examples/OpenSSHConfig.java @@ -1,8 +1,7 @@ /** - * This program demonsrates how to use OpenSSHConfig class. $ CLASSPATH=.:../build javac - * OpenSSHConfig.java $ CLASSPATH=.:../build java OpenSSHConfig You will be asked username, hostname - * and passwd. If everything works fine, you will get the shell prompt. Output may be ugly because - * of lacks of terminal-emulation, but you can issue commands. + * This program demonsrates how to use OpenSSHConfig class. You will be asked username, hostname and + * passwd. If everything works fine, you will get the shell prompt. Output may be ugly because of + * lacks of terminal-emulation, but you can issue commands. * */ import com.jcraft.jsch.*; @@ -46,10 +45,12 @@ public static void main(String[] arg) { session.setPassword(passwd); UserInfo ui = new MyUserInfo() { + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } + @Override public boolean promptYesNo(String message) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, message, "Warning", @@ -72,22 +73,21 @@ public boolean promptYesNo(String message) { Channel channel = session.openChannel("shell"); channel.setInputStream(System.in); - /* - * // a hack for MS-DOS prompt on Windows. channel.setInputStream(new - * FilterInputStream(System.in){ public int read(byte[] b, int off, int len)throws - * IOException{ return in.read(b, off, (len>1024?1024:len)); } }); - */ + // a hack for MS-DOS prompt on Windows. + // channel.setInputStream(new FilterInputStream(System.in) { + // @Override + // public int read(byte[] b, int off, int len) throws IOException { + // return in.read(b, off, len > 1024 ? 1024 : len); + // } + // }); channel.setOutputStream(System.out); - /* - * // Choose the pty-type "vt102". ((ChannelShell)channel).setPtyType("vt102"); - */ + // Choose the pty-type "vt102". + // ((ChannelShell) channel).setPtyType("vt102"); - /* - * // Set environment variable "LANG" as "ja_JP.eucJP". ((ChannelShell)channel).setEnv("LANG", - * "ja_JP.eucJP"); - */ + // Set environment variable "LANG" as "ja_JP.eucJP". + // ((ChannelShell) channel).setEnv("LANG", "ja_JP.eucJP"); // channel.connect(); channel.connect(3 * 1000); @@ -97,28 +97,27 @@ public boolean promptYesNo(String message) { } public static abstract class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return null; } - public boolean promptYesNo(String str) { - return false; - } - + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return false; } + @Override public boolean promptPassword(String message) { return false; } - public void showMessage(String message) {} - + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { return null; diff --git a/examples/PortForwardingL.java b/examples/PortForwardingL.java index 1751499c..1cd7a114 100644 --- a/examples/PortForwardingL.java +++ b/examples/PortForwardingL.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate the port forwarding like option -L of ssh command; the given port - * on the local host will be forwarded to the given remote host and port on the remote side. $ - * CLASSPATH=.:../build javac PortForwardingL.java $ CLASSPATH=.:../build java PortForwardingL You + * This program will demonstrate the port forwarding like option -L of ssh command. The given port + * on the local host will be forwarded to the given remote host and port on the remote side. You * will be asked username, hostname, port:host:hostport and passwd. If everything works fine, you * will get the shell prompt. Try the port on localhost. * @@ -44,7 +43,7 @@ public static void main(String[] arg) { session.connect(); - // Channel channel=session.openChannel("shell"); + // Channel channel = session.openChannel("shell"); // channel.connect(); int assinged_port = session.setPortForwardingL(lport, rhost, rport); @@ -55,10 +54,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -67,16 +68,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -88,6 +92,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -96,6 +101,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/PortForwardingR.java b/examples/PortForwardingR.java index 5325f01c..cb74ba18 100644 --- a/examples/PortForwardingR.java +++ b/examples/PortForwardingR.java @@ -1,9 +1,8 @@ /** * This program will demonstrate the port forwarding like option -R of ssh command; the given port - * on the remote host will be forwarded to the given host and port on the local side. $ - * CLASSPATH=.:../build javac PortForwardingR.java $ CLASSPATH=.:../build java PortForwardingR You - * will be asked username, hostname, port:host:hostport and passwd. If everything works fine, you - * will get the shell prompt. Try the port on remote host. + * on the remote host will be forwarded to the given host and port on the local side. You will be + * asked username, hostname, port:host:hostport and passwd. If everything works fine, you will get + * the shell prompt. Try the port on remote host. * */ import com.jcraft.jsch.*; @@ -44,7 +43,7 @@ public static void main(String[] arg) { session.connect(); - // Channel channel=session.openChannel("shell"); + // Channel channel = session.openChannel("shell"); // channel.connect(); session.setPortForwardingR(rport, lhost, lport); @@ -56,10 +55,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -68,16 +69,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -89,6 +93,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -97,6 +102,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/ScpFrom.java b/examples/ScpFrom.java index 27df1a96..756b8e55 100644 --- a/examples/ScpFrom.java +++ b/examples/ScpFrom.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate the file transfer from remote to local $ CLASSPATH=.:../build javac - * ScpFrom.java $ CLASSPATH=.:../build java ScpFrom user@remotehost:file1 file2 You will be asked - * passwd. If everything works fine, a file 'file1' on 'remotehost' will copied to local 'file1'. + * This program will demonstrate the file transfer from remote to local. If everything works fine, a + * file 'file1' on 'remotehost' will copied to local 'file1'. * */ import com.jcraft.jsch.*; @@ -16,7 +15,6 @@ public static void main(String[] arg) { System.exit(-1); } - FileOutputStream fos = null; try { String user = arg[0].substring(0, arg[0].indexOf('@')); @@ -87,7 +85,7 @@ public static void main(String[] arg) { } } - // System.out.println("filesize="+filesize+", file="+file); + // System.out.println("filesize=" + filesize + ", file=" + file); // send '\0' buf[0] = 0; @@ -95,25 +93,24 @@ public static void main(String[] arg) { out.flush(); // read a content of lfile - fos = new FileOutputStream(prefix == null ? lfile : prefix + file); - int foo; - while (true) { - if (buf.length < filesize) - foo = buf.length; - else - foo = (int) filesize; - foo = in.read(buf, 0, foo); - if (foo < 0) { - // error - break; + try (OutputStream fos = new FileOutputStream(prefix == null ? lfile : prefix + file)) { + int foo; + while (true) { + if (buf.length < filesize) + foo = buf.length; + else + foo = (int) filesize; + foo = in.read(buf, 0, foo); + if (foo < 0) { + // error + break; + } + fos.write(buf, 0, foo); + filesize -= foo; + if (filesize == 0L) + break; } - fos.write(buf, 0, foo); - filesize -= foo; - if (filesize == 0L) - break; } - fos.close(); - fos = null; if (checkAck(in) != 0) { System.exit(0); @@ -130,11 +127,6 @@ public static void main(String[] arg) { System.exit(0); } catch (Exception e) { System.out.println(e); - try { - if (fos != null) - fos.close(); - } catch (Exception ee) { - } } } @@ -150,27 +142,29 @@ static int checkAck(InputStream in) throws IOException { return b; if (b == 1 || b == 2) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1) { // error - System.out.print(sb.toString()); + System.out.print(sb); } if (b == 2) { // fatal error - System.out.print(sb.toString()); + System.out.print(sb); } } return b; } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -179,16 +173,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -200,6 +197,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -208,6 +206,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/ScpTo.java b/examples/ScpTo.java index 1cd6d222..46140172 100644 --- a/examples/ScpTo.java +++ b/examples/ScpTo.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate the file transfer from local to remote. $ CLASSPATH=.:../build - * javac ScpTo.java $ CLASSPATH=.:../build java ScpTo file1 user@remotehost:file2 You will be asked - * passwd. If everything works fine, a local file 'file1' will copied to 'file2' on 'remotehost'. + * This program will demonstrate the file transfer from local to remote. You will be asked passwd. + * If everything works fine, a local file 'file1' will copied to 'file2' on 'remotehost'. * */ import com.jcraft.jsch.*; @@ -16,7 +15,6 @@ public static void main(String[] arg) { System.exit(-1); } - FileInputStream fis = null; try { String lfile = arg[0]; @@ -33,12 +31,10 @@ public static void main(String[] arg) { session.setUserInfo(ui); session.connect(); - boolean ptimestamp = true; - // exec 'scp -t rfile' remotely rfile = rfile.replace("'", "'\"'\"'"); rfile = "'" + rfile + "'"; - String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile; + String command = "scp -p -t " + rfile; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); @@ -54,16 +50,14 @@ public static void main(String[] arg) { File _lfile = new File(lfile); - if (ptimestamp) { - command = "T " + (_lfile.lastModified() / 1000) + " 0"; - // The access time should be sent here, - // but it is not accessible with JavaAPI ;-< - command += (" " + (_lfile.lastModified() / 1000) + " 0\n"); - out.write(command.getBytes()); - out.flush(); - if (checkAck(in) != 0) { - System.exit(0); - } + command = "T " + (_lfile.lastModified() / 1000) + " 0"; + // The access time should be sent here, + // but it is not accessible with JavaAPI ;-< + command += " " + (_lfile.lastModified() / 1000) + " 0\n"; + out.write(command.getBytes()); + out.flush(); + if (checkAck(in) != 0) { + System.exit(0); } // send "C0644 filesize filename", where filename should not include '/' @@ -77,41 +71,38 @@ public static void main(String[] arg) { command += "\n"; out.write(command.getBytes()); out.flush(); + if (checkAck(in) != 0) { System.exit(0); } - // send a content of lfile - fis = new FileInputStream(lfile); byte[] buf = new byte[1024]; - while (true) { - int len = fis.read(buf, 0, buf.length); - if (len <= 0) - break; - out.write(buf, 0, len); // out.flush(); + + // send a content of lfile + try (InputStream fis = new FileInputStream(lfile)) { + while (true) { + int len = fis.read(buf, 0, buf.length); + if (len <= 0) + break; + out.write(buf, 0, len); + // out.flush(); + } } - fis.close(); - fis = null; + // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); + if (checkAck(in) != 0) { System.exit(0); } - out.close(); - channel.disconnect(); session.disconnect(); System.exit(0); } catch (Exception e) { System.out.println(e); - try { - if (fis != null) - fis.close(); - } catch (Exception ee) { - } } } @@ -127,27 +118,29 @@ static int checkAck(InputStream in) throws IOException { return b; if (b == 1 || b == 2) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1) { // error - System.out.print(sb.toString()); + System.out.print(sb); } if (b == 2) { // fatal error - System.out.print(sb.toString()); + System.out.print(sb); } } return b; } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -156,16 +149,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -177,6 +173,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -185,6 +182,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/ScpToNoneCipher.java b/examples/ScpToNoneCipher.java index 7d4eb439..f1752ca5 100644 --- a/examples/ScpToNoneCipher.java +++ b/examples/ScpToNoneCipher.java @@ -1,5 +1,6 @@ /** - * This program will demonstrate how to enable none cipher. + * This program will demonstrate how to enable none cipher. You will be asked passwd. If everything + * works fine, a local file 'file1' will copied to 'file2' on 'remotehost'. * */ import com.jcraft.jsch.*; @@ -14,7 +15,6 @@ public static void main(String[] arg) { System.exit(-1); } - FileInputStream fis = null; try { String lfile = arg[0]; @@ -53,8 +53,20 @@ public static void main(String[] arg) { System.exit(0); } + File _lfile = new File(lfile); + + command = "T " + (_lfile.lastModified() / 1000) + " 0"; + // The access time should be sent here, + // but it is not accessible with JavaAPI ;-< + command += " " + (_lfile.lastModified() / 1000) + " 0\n"; + out.write(command.getBytes()); + out.flush(); + if (checkAck(in) != 0) { + System.exit(0); + } + // send "C0644 filesize filename", where filename should not include '/' - long filesize = (new File(lfile)).length(); + long filesize = _lfile.length(); command = "C0644 " + filesize + " "; if (lfile.lastIndexOf('/') > 0) { command += lfile.substring(lfile.lastIndexOf('/') + 1); @@ -69,18 +81,18 @@ public static void main(String[] arg) { System.exit(0); } - // send a content of lfile - fis = new FileInputStream(lfile); byte[] buf = new byte[1024]; - while (true) { - int len = fis.read(buf, 0, buf.length); - if (len <= 0) - break; - out.write(buf, 0, len); - out.flush(); + + // send a content of lfile + try (InputStream fis = new FileInputStream(lfile)) { + while (true) { + int len = fis.read(buf, 0, buf.length); + if (len <= 0) + break; + out.write(buf, 0, len); + // out.flush(); + } } - fis.close(); - fis = null; // send '\0' buf[0] = 0; @@ -96,11 +108,6 @@ public static void main(String[] arg) { System.exit(0); } catch (Exception e) { System.out.println(e); - try { - if (fis != null) - fis.close(); - } catch (Exception ee) { - } } } @@ -116,27 +123,29 @@ static int checkAck(InputStream in) throws IOException { return b; if (b == 1 || b == 2) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1) { // error - System.out.print(sb.toString()); + System.out.print(sb); } if (b == 2) { // fatal error - System.out.print(sb.toString()); + System.out.print(sb); } } return b; } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -145,16 +154,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -166,6 +178,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -174,6 +187,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/Sftp.java b/examples/Sftp.java index 47ee5daa..1b79b413 100644 --- a/examples/Sftp.java +++ b/examples/Sftp.java @@ -1,9 +1,7 @@ /** - * This program will demonstrate the sftp protocol support. $ CLASSPATH=.:../build javac Sftp.java $ - * CLASSPATH=.:../build java Sftp You will be asked username, host and passwd. If everything works - * fine, you will get a prompt 'sftp>'. 'help' command will show available command. In current - * implementation, the destination path for 'get' and 'put' commands must be a file, not a - * directory. + * This program will demonstrate the sftp protocol support. If everything works fine, you will get a + * prompt 'sftp>'. 'help' command will show available command. In current implementation, the + * destination path for 'get' and 'put' commands must be a file, not a directory. * */ import com.jcraft.jsch.*; @@ -42,7 +40,7 @@ public static void main(String[] arg) { java.io.InputStream in = System.in; java.io.PrintStream out = System.out; - java.util.Vector cmds = new java.util.Vector(); + java.util.List cmds = new java.util.ArrayList<>(); byte[] buf = new byte[1024]; int i; String str; @@ -50,7 +48,7 @@ public static void main(String[] arg) { while (true) { out.print("sftp> "); - cmds.removeAllElements(); + cmds.clear(); i = in.read(buf, 0, 1024); if (i <= 0) break; @@ -58,13 +56,13 @@ public static void main(String[] arg) { i--; if (i > 0 && buf[i - 1] == 0x0d) i--; - // str=new String(buf, 0, i); - // System.out.println("|"+str+"|"); + // str = new String(buf, 0, i); + // System.out.println("|" + str + "|"); int s = 0; for (int ii = 0; ii < i; ii++) { if (buf[ii] == ' ') { if (ii - s > 0) { - cmds.addElement(new String(buf, s, ii - s)); + cmds.add(new String(buf, s, ii - s)); } while (ii < i) { if (buf[ii] != ' ') @@ -75,12 +73,12 @@ public static void main(String[] arg) { } } if (s < i) { - cmds.addElement(new String(buf, s, i - s)); + cmds.add(new String(buf, s, i - s)); } - if (cmds.size() == 0) + if (cmds.isEmpty()) continue; - String cmd = (String) cmds.elementAt(0); + String cmd = cmds.get(0); if (cmd.equals("quit")) { c.quit(); break; @@ -99,7 +97,7 @@ public static void main(String[] arg) { continue; } try { - level = Integer.parseInt((String) cmds.elementAt(1)); + level = Integer.parseInt(cmds.get(1)); if (level == 0) { session.setConfig("compression.s2c", "none"); session.setConfig("compression.c2s", "none"); @@ -115,21 +113,21 @@ public static void main(String[] arg) { if (cmd.equals("cd") || cmd.equals("lcd")) { if (cmds.size() < 2) continue; - String path = (String) cmds.elementAt(1); + String path = cmds.get(1); try { if (cmd.equals("cd")) c.cd(path); else c.lcd(path); } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } if (cmd.equals("rm") || cmd.equals("rmdir") || cmd.equals("mkdir")) { if (cmds.size() < 2) continue; - String path = (String) cmds.elementAt(1); + String path = cmds.get(1); try { if (cmd.equals("rm")) c.rm(path); @@ -138,20 +136,18 @@ else if (cmd.equals("rmdir")) else c.mkdir(path); } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } if (cmd.equals("chgrp") || cmd.equals("chown") || cmd.equals("chmod")) { if (cmds.size() != 3) continue; - String path = (String) cmds.elementAt(2); + String path = cmds.get(2); int foo = 0; if (cmd.equals("chmod")) { - byte[] bar = ((String) cmds.elementAt(1)).getBytes(); - int k; - for (int j = 0; j < bar.length; j++) { - k = bar[j]; + byte[] bar = cmds.get(1).getBytes(); + for (int k : bar) { if (k < '0' || k > '7') { foo = -1; break; @@ -163,7 +159,7 @@ else if (cmd.equals("rmdir")) continue; } else { try { - foo = Integer.parseInt((String) cmds.elementAt(1)); + foo = Integer.parseInt(cmds.get(1)); } catch (Exception e) { continue; } @@ -177,7 +173,7 @@ else if (cmd.equals("rmdir")) c.chmod(foo, path); } } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } @@ -194,29 +190,24 @@ else if (cmd.equals("rmdir")) if (cmd.equals("ls") || cmd.equals("dir")) { String path = "."; if (cmds.size() == 2) - path = (String) cmds.elementAt(1); + path = cmds.get(1); try { - java.util.Vector vv = c.ls(path); + java.util.Vector vv = c.ls(path); if (vv != null) { - for (int ii = 0; ii < vv.size(); ii++) { - // out.println(vv.elementAt(ii).toString()); - - Object obj = vv.elementAt(ii); - if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) { - out.println(((com.jcraft.jsch.ChannelSftp.LsEntry) obj).getLongname()); - } - + for (ChannelSftp.LsEntry le : vv) { + // out.println(le); + out.println(le.getLongname()); } } } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } if (cmd.equals("lls") || cmd.equals("ldir")) { String path = "."; if (cmds.size() == 2) - path = (String) cmds.elementAt(1); + path = cmds.get(1); try { java.io.File file = new java.io.File(path); if (!file.exists()) { @@ -225,8 +216,8 @@ else if (cmd.equals("rmdir")) } if (file.isDirectory()) { String[] list = file.list(); - for (int ii = 0; ii < list.length; ii++) { - out.println(list[ii]); + for (String l : list) { + out.println(l); } continue; } @@ -240,11 +231,11 @@ else if (cmd.equals("rmdir")) || cmd.equals("put") || cmd.equals("put-resume") || cmd.equals("put-append")) { if (cmds.size() != 2 && cmds.size() != 3) continue; - String p1 = (String) cmds.elementAt(1); - // String p2=p1; + String p1 = cmds.get(1); + // String p2 = p1; String p2 = "."; if (cmds.size() == 3) - p2 = (String) cmds.elementAt(2); + p2 = cmds.get(2); try { SftpProgressMonitor monitor = new MyProgressMonitor(); if (cmd.startsWith("get")) { @@ -265,7 +256,7 @@ else if (cmd.equals("rmdir")) c.put(p1, p2, monitor, mode); } } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } @@ -273,8 +264,8 @@ else if (cmd.equals("rmdir")) || cmd.equals("hardlink")) { if (cmds.size() != 3) continue; - String p1 = (String) cmds.elementAt(1); - String p2 = (String) cmds.elementAt(2); + String p1 = cmds.get(1); + String p2 = cmds.get(2); try { if (cmd.equals("hardlink")) { c.hardlink(p1, p2); @@ -283,14 +274,14 @@ else if (cmd.equals("rmdir")) else c.symlink(p1, p2); } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } if (cmd.equals("df")) { if (cmds.size() > 2) continue; - String p1 = cmds.size() == 1 ? "." : (String) cmds.elementAt(1); + String p1 = cmds.size() == 1 ? "." : cmds.get(1); SftpStatVFS stat = c.statVFS(p1); long size = stat.getSize(); @@ -310,7 +301,7 @@ else if (cmd.equals("rmdir")) if (cmd.equals("stat") || cmd.equals("lstat")) { if (cmds.size() != 2) continue; - String p1 = (String) cmds.elementAt(1); + String p1 = cmds.get(1); SftpATTRS attrs = null; try { if (cmd.equals("stat")) @@ -318,7 +309,7 @@ else if (cmd.equals("rmdir")) else attrs = c.lstat(p1); } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } if (attrs != null) { out.println(attrs); @@ -329,26 +320,26 @@ else if (cmd.equals("rmdir")) if (cmd.equals("readlink")) { if (cmds.size() != 2) continue; - String p1 = (String) cmds.elementAt(1); + String p1 = cmds.get(1); String filename = null; try { filename = c.readlink(p1); out.println(filename); } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } if (cmd.equals("realpath")) { if (cmds.size() != 2) continue; - String p1 = (String) cmds.elementAt(1); + String p1 = cmds.get(1); String filename = null; try { filename = c.realpath(p1); out.println(filename); } catch (SftpException e) { - System.out.println(e.toString()); + System.out.println(e); } continue; } @@ -370,10 +361,12 @@ else if (cmd.equals("rmdir")) } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -382,16 +375,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -403,6 +399,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -411,6 +408,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); @@ -456,28 +454,12 @@ public String[] promptKeyboardInteractive(String destination, String name, Strin } } - /* - * public static class MyProgressMonitor implements com.jcraft.jsch.ProgressMonitor{ JProgressBar - * progressBar; JFrame frame; long count=0; long max=0; - * - * public void init(String info, long max){ this.max=max; if(frame==null){ frame=new JFrame(); - * frame.setSize(200, 20); progressBar = new JProgressBar(); } count=0; - * - * frame.setTitle(info); progressBar.setMaximum((int)max); progressBar.setMinimum((int)0); - * progressBar.setValue((int)count); progressBar.setStringPainted(true); - * - * JPanel p=new JPanel(); p.add(progressBar); frame.getContentPane().add(progressBar); - * frame.setVisible(true); System.out.println("!info:"+info+", max="+max+" "+progressBar); } - * public void count(long count){ this.count+=count; System.out.println("count: "+count); - * progressBar.setValue((int)this.count); } public void end(){ System.out.println("end"); - * progressBar.setValue((int)this.max); frame.setVisible(false); } } - */ - public static class MyProgressMonitor implements SftpProgressMonitor { ProgressMonitor monitor; long count = 0; long max = 0; + @Override public void init(int op, String src, String dest, long max) { this.max = max; monitor = new ProgressMonitor(null, @@ -490,6 +472,7 @@ public void init(int op, String src, String dest, long max) { private long percent = -1; + @Override public boolean count(long count) { this.count += count; @@ -504,6 +487,7 @@ public boolean count(long count) { return !(monitor.isCanceled()); } + @Override public void end() { monitor.close(); } diff --git a/examples/Shell.java b/examples/Shell.java index 4e8b7ae9..9db4fe95 100644 --- a/examples/Shell.java +++ b/examples/Shell.java @@ -1,6 +1,5 @@ /** - * This program enables you to connect to sshd server and get the shell prompt. $ - * CLASSPATH=.:../build javac Shell.java $ CLASSPATH=.:../build java Shell You will be asked + * This program enables you to connect to sshd server and get the shell prompt. You will be asked * username, hostname and passwd. If everything works fine, you will get the shell prompt. Output * may be ugly because of lacks of terminal-emulation, but you can issue commands. * @@ -33,10 +32,12 @@ public static void main(String[] arg) { session.setPassword(passwd); UserInfo ui = new MyUserInfo() { + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } + @Override public boolean promptYesNo(String message) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, message, "Warning", @@ -64,25 +65,24 @@ public boolean promptYesNo(String message) { Channel channel = session.openChannel("shell"); // Enable agent-forwarding. - // ((ChannelShell)channel).setAgentForwarding(true); + // ((ChannelShell) channel).setAgentForwarding(true); channel.setInputStream(System.in); - /* - * // a hack for MS-DOS prompt on Windows. channel.setInputStream(new - * FilterInputStream(System.in){ public int read(byte[] b, int off, int len)throws - * IOException{ return in.read(b, off, (len>1024?1024:len)); } }); - */ + // a hack for MS-DOS prompt on Windows. + // channel.setInputStream(new FilterInputStream(System.in) { + // @Override + // public int read(byte[] b, int off, int len) throws IOException { + // return in.read(b, off, len > 1024 ? 1024 : len); + // } + // }); channel.setOutputStream(System.out); - /* - * // Choose the pty-type "vt102". ((ChannelShell)channel).setPtyType("vt102"); - */ + // Choose the pty-type "vt102". + // ((ChannelShell) channel).setPtyType("vt102"); - /* - * // Set environment variable "LANG" as "ja_JP.eucJP". ((ChannelShell)channel).setEnv("LANG", - * "ja_JP.eucJP"); - */ + // Set environment variable "LANG" as "ja_JP.eucJP". + // ((ChannelShell) channel).setEnv("LANG", "ja_JP.eucJP"); // channel.connect(); channel.connect(3 * 1000); @@ -92,28 +92,27 @@ public boolean promptYesNo(String message) { } public static abstract class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return null; } - public boolean promptYesNo(String str) { - return false; - } - + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return false; } + @Override public boolean promptPassword(String message) { return false; } - public void showMessage(String message) {} - + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { return null; diff --git a/examples/SocketForwardingL.java b/examples/SocketForwardingL.java index 2a21ef69..51b78d38 100644 --- a/examples/SocketForwardingL.java +++ b/examples/SocketForwardingL.java @@ -1,10 +1,9 @@ /** - * This program enables you to connect to sshd server and forward the docker socket. $ - * CLASSPATH=.:../build javac SocketForwardingL.java $ CLASSPATH=.:../build java SocketForwardingL - * You will be asked username, hostname and passwd. If everything works fine, you will get the - * response code to the _ping endpoint of the dockerd. + * This program enables you to connect to sshd server and forward the docker socket. You will be + * asked username, hostname and passwd. If everything works fine, you will get the response code to + * the _ping endpoint of the dockerd. + * */ - import com.jcraft.jsch.*; import javax.swing.*; @@ -33,10 +32,12 @@ public static void main(String[] arg) { session.setPassword(passwd); UserInfo ui = new MyUserInfo() { + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } + @Override public boolean promptYesNo(String message) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, message, "Warning", @@ -81,28 +82,27 @@ public boolean promptYesNo(String message) { } public static abstract class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return null; } - public boolean promptYesNo(String str) { - return false; - } - + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return false; } + @Override public boolean promptPassword(String message) { return false; } - public void showMessage(String message) {} - + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { return null; diff --git a/examples/StreamForwarding.java b/examples/StreamForwarding.java index e666f585..47a360bd 100644 --- a/examples/StreamForwarding.java +++ b/examples/StreamForwarding.java @@ -1,8 +1,7 @@ /** * This program will demonstrate the stream forwarding. The given Java I/O streams will be forwared - * to the given remote host and port on the remote side. It is simmilar to the -L option of ssh - * command, but you don't have to assign and open a local tcp port. $ CLASSPATH=.:../build javac - * StreamForwarding.java $ CLASSPATH=.:../build java StreamForwarding You will be asked username, + * to the given remote host and port on the remote side. It is similar to the -L option of ssh + * command, but you don't have to assign and open a local tcp port. You will be asked username, * hostname, host:hostport and passwd. If everything works fine, System.in and System.out streams * will be forwared to remote port and you can send messages from command line. * @@ -52,10 +51,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -64,16 +65,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -85,6 +89,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -93,6 +98,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/Subsystem.java b/examples/Subsystem.java index 2e2d37fa..fa4065f7 100644 --- a/examples/Subsystem.java +++ b/examples/Subsystem.java @@ -38,25 +38,42 @@ public static void main(String[] arg) { channel.setOutputStream(System.out); channel.connect(); - /* - * channel.setInputStream(System.in); ((ChannelSubsystem)channel).setErrStream(System.err); - * InputStream in = channel.getInputStream(); channel.connect(); - * - * byte[] tmp=new byte[1024]; while(true){ while(in.available()>0){ int i=in.read(tmp, 0, - * 1024); if(i<0)break; System.out.print(new String(tmp, 0, i)); } if(channel.isClosed()){ - * System.out.println("exit-status: "+channel.getExitStatus()); break; } - * try{Thread.sleep(1000);}catch(Exception ee){} } channel.disconnect(); session.disconnect(); - */ + // channel.setInputStream(System.in); + // ((ChannelSubsystem) channel).setErrStream(System.err); + // InputStream in = channel.getInputStream(); + // channel.connect(); + // + // byte[] tmp = new byte[1024]; + // while (true) { + // while (in.available() > 0) { + // int i = in.read(tmp, 0, 1024); + // if (i < 0) + // break; + // System.out.print(new String(tmp, 0, i)); + // } + // if (channel.isClosed()) { + // System.out.println("exit-status: " + channel.getExitStatus()); + // break; + // } + // try { + // Thread.sleep(1000); + // } catch (Exception ee) { + // } + // } + // channel.disconnect(); + // session.disconnect(); } catch (Exception e) { System.out.println(e); } } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -65,16 +82,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -86,6 +106,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -94,6 +115,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/Sudo.java b/examples/Sudo.java index 67a6eb21..e0b8ec1b 100644 --- a/examples/Sudo.java +++ b/examples/Sudo.java @@ -33,7 +33,7 @@ public static void main(String[] arg) { String sudo_pass = null; { - JTextField passwordField = (JTextField) new JPasswordField(8); + JTextField passwordField = new JPasswordField(8); Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, "Enter password for sudo", JOptionPane.OK_CANCEL_OPTION); @@ -87,10 +87,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -99,16 +101,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -120,6 +125,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -128,6 +134,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/UserAuthKI.java b/examples/UserAuthKI.java index accd7e74..67cfdd06 100644 --- a/examples/UserAuthKI.java +++ b/examples/UserAuthKI.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate the keyboard-interactive authentication. $ CLASSPATH=.:../build - * javac UserAuthKI.java $ CLASSPATH=.:../build java UserAuthKI If the remote sshd supports - * keyboard-interactive authentication, you will be prompted. + * This program will demonstrate the keyboard-interactive authentication. If the remote sshd + * supports keyboard-interactive authentication, you will be prompted. * */ import com.jcraft.jsch.*; @@ -43,10 +42,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -55,16 +56,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return false; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -76,6 +80,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -84,15 +89,15 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { - /* - * //System.out.println("promptKeyboardInteractive"); - * System.out.println("destination: "+destination); System.out.println("name: "+name); - * System.out.println("instruction: "+instruction); - * System.out.println("prompt.length: "+prompt.length); - * System.out.println("prompt: "+prompt[0]); - */ + // System.out.println("promptKeyboardInteractive"); + // System.out.println("destination: " + destination); + // System.out.println("name: " + name); + // System.out.println("instruction: " + instruction); + // System.out.println("prompt.length: " + prompt.length); + // System.out.println("prompt: " + prompt[0]); panel = new JPanel(); panel.setLayout(new GridBagLayout()); diff --git a/examples/UserAuthPubKey.java b/examples/UserAuthPubKey.java index 57ae62a2..6ed96078 100644 --- a/examples/UserAuthPubKey.java +++ b/examples/UserAuthPubKey.java @@ -1,8 +1,7 @@ /** - * This program will demonstrate the user authentification by public key. $ CLASSPATH=.:../build - * javac UserAuthPubKey.java $ CLASSPATH=.:../build java UserAuthPubKey You will be asked username, - * hostname, privatekey(id_dsa) and passphrase. If everything works fine, you will get the shell - * prompt + * This program will demonstrate the user authentification by public key. You will be asked + * username, hostname, privatekey(id_dsa) and passphrase. If everything works fine, you will get the + * shell prompt. * */ import com.jcraft.jsch.*; @@ -56,10 +55,12 @@ public static void main(String[] arg) { public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return null; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -68,12 +69,14 @@ public boolean promptYesNo(String str) { } String passphrase; - JTextField passphraseField = (JTextField) new JPasswordField(20); + JTextField passphraseField = new JPasswordField(20); + @Override public String getPassphrase() { return passphrase; } + @Override public boolean promptPassphrase(String message) { Object[] ob = {passphraseField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -85,10 +88,12 @@ public boolean promptPassphrase(String message) { } } + @Override public boolean promptPassword(String message) { return true; } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -97,6 +102,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/ViaHTTP.java b/examples/ViaHTTP.java index 054e9a1b..5d3ea03d 100644 --- a/examples/ViaHTTP.java +++ b/examples/ViaHTTP.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate the ssh session via HTTP proxy. $ CLASSPATH=.:../build javac - * ViaHTTP.java $ CLASSPATH=.:../build java ViaHTTP You will be asked username, hostname, - * proxy-server and passwd. If everything works fine, you will get the shell prompt. + * This program will demonstrate the ssh session via HTTP proxy. You will be asked username, + * hostname, proxy-server and passwd. If everything works fine, you will get the shell prompt. * */ import com.jcraft.jsch.*; @@ -53,10 +52,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -65,16 +66,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -86,6 +90,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -94,6 +99,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/ViaSOCKS5.java b/examples/ViaSOCKS5.java index 3ac76a9a..8ee9fdec 100644 --- a/examples/ViaSOCKS5.java +++ b/examples/ViaSOCKS5.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate the ssh session via SOCKS proxy. $ CLASSPATH=.:../build javac - * ViaSOCKS.java $ CLASSPATH=.:../build java ViaSOCKS You will be asked username, hostname, - * proxy-server and passwd. If everything works fine, you will get the shell prompt. + * This program will demonstrate the ssh session via SOCKS proxy. You will be asked username, + * hostname, proxy-server and passwd. If everything works fine, you will get the shell prompt. * */ import com.jcraft.jsch.*; @@ -53,10 +52,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -65,16 +66,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -86,6 +90,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -94,6 +99,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); diff --git a/examples/X11Forwarding.java b/examples/X11Forwarding.java index fa4ab8a7..95d9fa1c 100644 --- a/examples/X11Forwarding.java +++ b/examples/X11Forwarding.java @@ -1,7 +1,6 @@ /** - * This program will demonstrate X11 forwarding. $ CLASSPATH=.:../build javac X11Forwarding.java $ - * CLASSPATH=.:../build java X11Forwarding You will be asked username, hostname, displayname and - * passwd. If your X server does not run at 127.0.0.1, please enter correct displayname. If + * This program will demonstrate X11 forwarding. You will be asked username, hostname, displayname + * and passwd. If your X server does not run at 127.0.0.1, please enter correct displayname. If * everything works fine, you will get the shell prompt. Try X applications; for example, xlogo. * */ @@ -57,10 +56,12 @@ public static void main(String[] arg) { } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + @Override public String getPassword() { return passwd; } + @Override public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, str, "Warning", JOptionPane.DEFAULT_OPTION, @@ -69,16 +70,19 @@ public boolean promptYesNo(String str) { } String passwd; - JTextField passwordField = (JTextField) new JPasswordField(20); + JTextField passwordField = new JPasswordField(20); + @Override public String getPassphrase() { return null; } + @Override public boolean promptPassphrase(String message) { return true; } + @Override public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); @@ -90,6 +94,7 @@ public boolean promptPassword(String message) { } } + @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @@ -98,6 +103,7 @@ public void showMessage(String message) { GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); From f52b46cb39ef08f295cf97f81f0b3ddddd6fada0 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Wed, 15 Mar 2023 06:23:34 -0500 Subject: [PATCH 05/11] Update to latest Surefire plugin. --- pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index afd4966a..a26758be 100644 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,7 @@ 2.6.2 5.13.0 2.20.0 + 3.0.0 @@ -404,7 +405,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + ${surefire.version} false @@ -412,7 +413,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 2.22.2 + ${surefire.version} false From f2c456f817a8a3eae6fe42199f657e889df3b95c Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Wed, 15 Mar 2023 06:26:11 -0500 Subject: [PATCH 06/11] Move assembly descriptor out of main directory. --- pom.xml | 2 +- src/{main => }/assembly/sources.xml | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename src/{main => }/assembly/sources.xml (100%) diff --git a/pom.xml b/pom.xml index a26758be..b38c51eb 100644 --- a/pom.xml +++ b/pom.xml @@ -487,7 +487,7 @@ - ${project.basedir}/src/main/assembly/sources.xml + ${project.basedir}/src/assembly/sources.xml diff --git a/src/main/assembly/sources.xml b/src/assembly/sources.xml similarity index 100% rename from src/main/assembly/sources.xml rename to src/assembly/sources.xml From 7bc05e81029f9fa4c26d86b6e51efefff4389c3f Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Wed, 15 Mar 2023 06:30:39 -0500 Subject: [PATCH 07/11] Add missing xml declarations. --- pom.xml | 1 + src/assembly/sources.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index b38c51eb..331466f1 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 com.github.mwiede diff --git a/src/assembly/sources.xml b/src/assembly/sources.xml index c9e4ac9a..d8c1808e 100644 --- a/src/assembly/sources.xml +++ b/src/assembly/sources.xml @@ -1,3 +1,4 @@ + sources false From 4762f1ab5969aafa7df3720696eeba2d1e56a216 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Wed, 15 Mar 2023 06:52:50 -0500 Subject: [PATCH 08/11] Use Log4j strict configuration syntax. --- src/test/resources/Log4j2LoggerTest.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/resources/Log4j2LoggerTest.xml b/src/test/resources/Log4j2LoggerTest.xml index 31187168..65413dfc 100644 --- a/src/test/resources/Log4j2LoggerTest.xml +++ b/src/test/resources/Log4j2LoggerTest.xml @@ -1,8 +1,8 @@ - + - - + + From 02d01c0ae6433770799684ae43ca029758020b5f Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 20 Mar 2023 06:16:07 -0500 Subject: [PATCH 09/11] Update dependencies. --- .mvn/wrapper/maven-wrapper.properties | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 08ea486a..d8b2495a 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -14,5 +14,5 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.0/apache-maven-3.9.0-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.1/apache-maven-3.9.1-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/pom.xml b/pom.xml index 331466f1..0559794b 100644 --- a/pom.xml +++ b/pom.xml @@ -121,7 +121,7 @@ org.slf4j slf4j-api - 2.0.6 + 2.0.7 true @@ -250,7 +250,7 @@ org.codehaus.mojo flatten-maven-plugin - 1.3.0 + 1.4.0 ossrh all From a09f4cc7798603a51040f6ee6171f44d485fb2c2 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 20 Mar 2023 22:04:14 -0500 Subject: [PATCH 10/11] Update release plugin and make build reproducible. --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0559794b..61ad4c51 100644 --- a/pom.xml +++ b/pom.xml @@ -73,6 +73,7 @@ + 2023-03-21T03:04:14Z UTF-8 UTF-8 true @@ -529,7 +530,7 @@ org.apache.maven.plugins maven-release-plugin - 2.5.3 + 3.0.0 false release From 7623c8e410bd7760a5c255b6f52e80e12f12d3ab Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Mon, 20 Mar 2023 22:52:53 -0500 Subject: [PATCH 11/11] Use StandardCharsets instances. --- .../java/com/jcraft/jsch/KnownHostsTest.java | 35 ++++++++++--------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/test/java/com/jcraft/jsch/KnownHostsTest.java b/src/test/java/com/jcraft/jsch/KnownHostsTest.java index 803a44df..527aad56 100644 --- a/src/test/java/com/jcraft/jsch/KnownHostsTest.java +++ b/src/test/java/com/jcraft/jsch/KnownHostsTest.java @@ -1,5 +1,7 @@ package com.jcraft.jsch; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -113,7 +115,7 @@ void setKnownHosts(InputStream input) throws JSchException { File hostFile = File.createTempFile("setknownhosts", ".txt"); try { try (FileOutputStream fos = new FileOutputStream(hostFile)) { - fos.write("some host data".getBytes("8859_1")); + fos.write("some host data".getBytes(ISO_8859_1)); } System.setProperty("user.home", hostFile.getParentFile().getAbsolutePath()); kh.setKnownHosts("some_filename:that can't exist"); @@ -208,7 +210,7 @@ void testSetKnownHostsHashedHost() throws Exception { // comment with umlaut to check used charset for dump kh.setKnownHosts( new ByteArrayInputStream((hashValue + " " + "ssh-rsa " + rsaKey + " some comment\r\n" - + "# 192.168.1.61 ssh-rsa MYRSAKEY some other commänt").getBytes("utf8"))); + + "# 192.168.1.61 ssh-rsa MYRSAKEY some other commänt").getBytes(UTF_8))); assertEquals(0, messages.size(), "no messages expected"); HostKey[] keys = kh.getHostKey(); @@ -237,7 +239,7 @@ void testSetKnownHostsDirectHost() throws Exception { KnownHosts kh = new KnownHosts(jsch); kh.setKnownHosts(new ByteArrayInputStream( ("@cert-authority " + hostLine + " " + "ssh-rsa " + rsaKey + " some comment") - .getBytes("8859_1"))); + .getBytes(ISO_8859_1))); assertEquals(0, messages.size(), "no messages expected"); HostKey[] keys = kh.getHostKey(); @@ -262,7 +264,7 @@ void testSetKnownHostsDirectHost() throws Exception { kh.setKnownHosts(new ByteArrayInputStream( ("!ssh.example.com,!192.168.1.61 " + "ssh-rsa " + rsaKey + " some comment") - .getBytes("8859_1"))); + .getBytes(ISO_8859_1))); assertEquals(0, messages.size(), "no messages expected"); keys = kh.getHostKey(); checkResultForKeyResult(keys, rsaKey, "!ssh.example.com,!192.168.1.61", ""); @@ -314,7 +316,7 @@ synchronized void sync(String foo) throws IOException { void dump(OutputStream out) { messages.add("stream based dump called with stream: " + out.getClass().getName()); try { - out.write("some dump data".getBytes("8859_1")); + out.write("some dump data".getBytes(ISO_8859_1)); } catch (IOException ioe) { Assertions.fail("exception occurred while trying to write dump to tream", ioe); } @@ -382,28 +384,28 @@ void testDumpHostKey() throws Exception { KnownHosts kh = new KnownHosts(jsch); kh.dumpHostKey(sink, - new HostKey("", "hostwithoutmarker", HostKey.SSHRSA, "rsakey".getBytes("8859_1"), null)); + new HostKey("", "hostwithoutmarker", HostKey.SSHRSA, "rsakey".getBytes(ISO_8859_1), null)); assertEquals("hostwithoutmarker ssh-rsa cnNha2V5\n", sink.toString("utf8"), "check dumped key"); sink.reset(); kh.dumpHostKey(sink, new HostKey("@somemarker", "hostwithmarker", HostKey.SSHRSA, - "rsakey".getBytes("8859_1"), null)); + "rsakey".getBytes(ISO_8859_1), null)); assertEquals("@somemarker hostwithmarker ssh-rsa cnNha2V5\n", sink.toString("utf8"), "check dumped key"); sink.reset(); kh.dumpHostKey(sink, new HostKey("", "hostwithoutmarker", HostKey.SSHRSA, - "rsakey".getBytes("8859_1"), "some commänt")); + "rsakey".getBytes(ISO_8859_1), "some commänt")); assertEquals("hostwithoutmarker ssh-rsa cnNha2V5 some commänt\n", sink.toString("utf8"), "check dumped key"); sink.reset(); kh.dumpHostKey(sink, new HostKey("@somemarker", "hostwithmarker", HostKey.SSHRSA, - "rsakey".getBytes("8859_1"), "some commänt")); + "rsakey".getBytes(ISO_8859_1), "some commänt")); assertEquals("@somemarker hostwithmarker ssh-rsa cnNha2V5 some commänt\n", sink.toString("utf8"), "check dumped key"); sink.reset(); kh.dumpHostKey(sink, new HostKey("", "hostwithoutmarker", HostKey.UNKNOWN, - "rsakey".getBytes("8859_1"), "some commänt")); + "rsakey".getBytes(ISO_8859_1), "some commänt")); assertEquals("hostwithoutmarker\n", sink.toString("utf8"), "check dumped key"); sink.reset(); } @@ -434,7 +436,7 @@ void testCreateHashedKey() throws Exception { kh.hmacsha1 = null; // this will lead to an NPE if the creation uses this instance try { - kh.createHashedHostKey("host.example.com", " ssh-rsa".getBytes("8859_1")); + kh.createHashedHostKey("host.example.com", " ssh-rsa".getBytes(ISO_8859_1)); fail("exception expected"); } catch (NullPointerException npe) { // expected but messages differ between java versions, so we don't check the message @@ -442,7 +444,8 @@ void testCreateHashedKey() throws Exception { } kh.hmacsha1 = new HMACSHA256(); - HostKey hostKey = kh.createHashedHostKey("host.example.com", " ssh-rsa".getBytes("8859_1")); + HostKey hostKey = + kh.createHashedHostKey("host.example.com", " ssh-rsa".getBytes(ISO_8859_1)); assertNotNull(hostKey, "returned host key shouldn't be null"); assertEquals(HashedHostKey.class.getName(), hostKey.getClass().getName(), "check type of returned host key"); @@ -792,7 +795,7 @@ public void testCheck() throws Exception { "invalid syntax should return NOT_INCLUDED"); assertEquals(KnownHosts.CHANGED, - kh.check("host.example.com", " ssh-rsa1234".getBytes("8859_1")), + kh.check("host.example.com", " ssh-rsa1234".getBytes(ISO_8859_1)), "changed key should return CHANGED"); assertEquals(KnownHosts.NOT_INCLUDED, kh.check("host2.example.com", rsaKeyBytes), "host mismatch should return NOT_INCLUDED"); @@ -888,7 +891,7 @@ void sync() throws IOException { getHostKeysString(hosts), "unexpected hosts"); assertEquals("", getMessagesAsString(), "unexpected messages"); - kh.remove("[192.277.325.5]:123", "ssh-rsa", " ssh-rsa1234".getBytes("8859_1")); + kh.remove("[192.277.325.5]:123", "ssh-rsa", " ssh-rsa1234".getBytes(ISO_8859_1)); hosts = kh.getHostKey(); assertEquals(3, hosts.length, "unexpected number of host keys: " + getHostKeysString(hosts)); assertEquals( @@ -1029,10 +1032,10 @@ private void checkSHA1HashResult(HashedHostKey hhk, String expectedMarker, Strin assertEquals(expectedType, hhk.getType(), "type mismatch"); assertTrue(hhk.isHashed(), "key should report itself hashed"); assertEquals("AAECAwQFBgcICQoLDA0ODxAREhM=", - new String(Util.toBase64(hhk.salt, 0, hhk.salt.length, true), "8859_1"), + new String(Util.toBase64(hhk.salt, 0, hhk.salt.length, true), ISO_8859_1), "salt should be null"); assertEquals("/pE4peaossRYDRp6bEWa348eFLI=", - new String(Util.toBase64(hhk.hash, 0, hhk.hash.length, true), "8859_1"), + new String(Util.toBase64(hhk.hash, 0, hhk.hash.length, true), ISO_8859_1), "salt should be null"); }