diff --git a/README.md b/README.md index f625d6a..217fba1 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,10 @@ Rewrite simple Shadowsocks with Java. It will remove complex funtions. -This need JDK 8. +Compatible with Java 7. #Current state: -Simple server + client. Version 0.7 +Simple server + client. Version 0.7.1 Support these args: @@ -26,29 +26,36 @@ Support these args: 8. -L Local mode(client, default) 9. -c config file 10. -t timeout(unit is second) + 11. -h show help. Crypto method: - 1. AES-128-CFB - 2. AES-192-CFB - 3. AES-256-CFB - 4. Chacha20 + 1. aes-128-cfb/ofb + 2. aes-192-cfb/ofb + 3. aes-256-cfb/ofb + 4. chacha20 One time auth feature done. -Support JSON config file.(local\_address/fast\_open/workers is not support) +Support JSON config file. + 1. local\_address/fast\_open/workers is not support. + 2. server\_mode is the additional item to set the running mode, server or client. You could refer to demo config etc/demo.json. How to run: =========== ### (1) Before you start -You must have 'gradle' installed first. +You must have 'gradle' installed first, or use gradle wrapper ./gradlew to download and config gradle. ### (2) generate distributable zip ``` $ gradle distZip ``` +or +``` +$ ./gradlew distZip +``` Then you will get shadowsocks-xx.zip in build/distributions. Unzip it, the folder should contain bin and lib. @@ -65,6 +72,11 @@ $ bin/shadowsocks -L ... ``` $ gradle fatJar ``` +or +``` +$ ./gradlew fatJar +``` + Then you will get shadowsocks-fat-xx.jar in build/libs. diff --git a/build.gradle b/build.gradle index 41cc875..784896a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -version '0.7' +version '0.7.1' apply plugin: 'java' apply plugin: 'jacoco' @@ -19,11 +19,9 @@ dependencies { testCompile 'junit:junit:4.12' } -jacocoTestReport { - reports { - xml.enabled = true - html.enabled = true - } +compileJava { + options.encoding = 'UTF-8' + options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" } mainClassName = 'shadowsocks.Main' @@ -44,4 +42,10 @@ task ('fatJar', type: Jar, dependsOn: classes){ exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' } +jacocoTestReport { + reports { + xml.enabled = true + html.enabled = true + } +} check.dependsOn jacocoTestReport diff --git a/etc/demo.json b/etc/demo.json index ab5a84b..47a8816 100644 --- a/etc/demo.json +++ b/etc/demo.json @@ -1,5 +1,6 @@ { "server":"my_server_ip", + "server_mode":false, "server_port":8388, "local_port":1080, "password":"mypassword", diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..ca78035 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..418a0bb --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Jul 11 13:10:50 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..27309d9 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +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" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f6d5974 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..ff1b73c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,19 @@ +/* + * This settings file was auto generated by the Gradle buildInit task + * by 'NU11' at '7/11/16 1:10 PM' with Gradle 2.13 + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/2.13/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = 'shadowsocks-java' diff --git a/src/main/java/shadowsocks/Main.java b/src/main/java/shadowsocks/Main.java index 44006f9..273f911 100644 --- a/src/main/java/shadowsocks/Main.java +++ b/src/main/java/shadowsocks/Main.java @@ -26,12 +26,14 @@ public class Main{ public static Logger log = LogManager.getLogger(Main.class.getName()); - public static final String VERSION = "0.7"; + public static final String VERSION = "0.7.1"; public static void main(String argv[]) { log.info("Shadowsocks " + VERSION); - GlobalConfig.getConfigFromArgv(argv); + if (!GlobalConfig.getConfigFromArgv(argv)) { + return; + } GlobalConfig.getConfigFromFile(); //make sure this method could work. try{ diff --git a/src/main/java/shadowsocks/Shadowsocks.java b/src/main/java/shadowsocks/Shadowsocks.java index 9b9760a..98f4768 100644 --- a/src/main/java/shadowsocks/Shadowsocks.java +++ b/src/main/java/shadowsocks/Shadowsocks.java @@ -72,12 +72,12 @@ private void setState(int state){ } } - public Shadowsocks(boolean server){ + public Shadowsocks(boolean isServer){ setState(STOP); mExecutorService = Executors.newCachedThreadPool(); - mIsServer = server; - mName = (server?"server":"local") + "[" + this.hashCode() + "]"; - mPort = server?GlobalConfig.get().getPort():GlobalConfig.get().getLocalPort(); + mIsServer = isServer; + mName = (isServer ? "server" : "local") + "[" + this.hashCode() + "]"; + mPort = isServer ? GlobalConfig.get().getPort() : GlobalConfig.get().getLocalPort(); } private TcpWorker createWorker(SocketChannel sc, boolean server){ diff --git a/src/main/java/shadowsocks/nio/tcp/LocalTcpWorker.java b/src/main/java/shadowsocks/nio/tcp/LocalTcpWorker.java index 058d2f9..7535eda 100644 --- a/src/main/java/shadowsocks/nio/tcp/LocalTcpWorker.java +++ b/src/main/java/shadowsocks/nio/tcp/LocalTcpWorker.java @@ -59,7 +59,7 @@ public class LocalTcpWorker extends TcpWorker { */ private void parseHeader() throws IOException { - SocketChannel local = mSession.get(true); + SocketChannel local = mSession.getSocketChannel(true); ByteBuffer bb = BufferHelper.create(512); //skip method list (max 1+1+255) @@ -97,13 +97,13 @@ private void parseHeader() throws IOException throw new IOException("Mode = " + header[1] + ", should be 1"); } - mStreamUpData.reset(); + mStreamUpBuffer.reset(); int addrtype = (int)(header[3] & 0xff); //add OTA flag if (mOneTimeAuth) { header[3] |= Session.OTA_FLAG; } - mStreamUpData.write(header[3]); + mStreamUpBuffer.write(header[3]); //get addr StringBuffer addr = new StringBuffer(); @@ -116,14 +116,14 @@ private void parseHeader() throws IOException headerSize -= 4; bb.get(ipv4); addr.append(InetAddress.getByAddress(ipv4).toString()); - mStreamUpData.write(ipv4); + mStreamUpBuffer.write(ipv4); }else if (addrtype == Session.ADDR_TYPE_HOST) { //get address len if (headerSize < 2) { throw new IOException("Host address is too short."); } int len = (bb.get() & 0xff); - mStreamUpData.write(len); + mStreamUpBuffer.write(len); headerSize -= 1; //get address if (headerSize < len) { @@ -132,7 +132,7 @@ private void parseHeader() throws IOException byte [] host = new byte[len]; bb.get(host); addr.append(new String(host)); - mStreamUpData.write(host); + mStreamUpBuffer.write(host); headerSize -= len; } else { //do not support other addrtype now. @@ -154,32 +154,32 @@ private void parseHeader() throws IOException addr.append(port); mConfig.target = addr.toString(); - mStreamUpData.write(bb.get()); - mStreamUpData.write(bb.get()); + mStreamUpBuffer.write(bb.get()); + mStreamUpBuffer.write(bb.get()); } private void replyToProxyProgram(byte [] msg) throws IOException { - SocketChannel local = mSession.get(true); + SocketChannel local = mSession.getSocketChannel(true); local.write(ByteBuffer.wrap(msg)); } private void sendHeaderToRemote() throws IOException, AuthException, CryptoException { - SocketChannel remote = mSession.get(false); + SocketChannel remote = mSession.getSocketChannel(false); // Create auth head if (mOneTimeAuth){ - byte [] authKey = SSAuth.prepareKey(mCryptor.getIV(true), mCryptor.getKey()); - byte [] authData = mStreamUpData.toByteArray(); + byte [] authKey = SSAuth.prepareKey(mCrypto.getIV(true), mCrypto.getKey()); + byte [] authData = mStreamUpBuffer.toByteArray(); byte [] authResult = mAuthor.doAuth(authKey, authData); - mStreamUpData.write(authResult); + mStreamUpBuffer.write(authResult); } //Send head to remote - byte [] headerData = mStreamUpData.toByteArray(); - byte [] result = mCryptor.encrypt(headerData, headerData.length); + byte [] headerData = mStreamUpBuffer.toByteArray(); + byte [] result = mCrypto.encrypt(headerData, headerData.length); BufferHelper.send(remote, result); } @@ -201,25 +201,25 @@ protected boolean relay(SocketChannel source, SocketChannel target, int direct) byte [] result; if (direct == Session.LOCAL2REMOTE) { - mStreamUpData.reset(); + mStreamUpBuffer.reset(); if (mOneTimeAuth) { ByteBuffer len = ByteBuffer.allocate(2); len.putShort((short)size); //chunk length 2 bytes - mStreamUpData.write(len.array()); + mStreamUpBuffer.write(len.array()); //auth result 10 bytes - byte [] authKey = SSAuth.prepareKey(mCryptor.getIV(true), mChunkCount); + byte [] authKey = SSAuth.prepareKey(mCrypto.getIV(true), mChunkCount); byte [] authData = new byte[size]; System.arraycopy(bb.array(), 0, authData, 0, size); byte [] authResult = mAuthor.doAuth(authKey, authData); - mStreamUpData.write(authResult); + mStreamUpBuffer.write(authResult); mChunkCount++; } - mStreamUpData.write(bb.array(), 0, size); - byte [] data = mStreamUpData.toByteArray(); - result = mCryptor.encrypt(data, data.length); + mStreamUpBuffer.write(bb.array(), 0, size); + byte [] data = mStreamUpBuffer.toByteArray(); + result = mCrypto.encrypt(data, data.length); }else{ - result = mCryptor.decrypt(bb.array(), size); + result = mCrypto.decrypt(bb.array(), size); } BufferHelper.send(target, result); return false; diff --git a/src/main/java/shadowsocks/nio/tcp/ServerTcpWorker.java b/src/main/java/shadowsocks/nio/tcp/ServerTcpWorker.java index ccd49c7..781202c 100644 --- a/src/main/java/shadowsocks/nio/tcp/ServerTcpWorker.java +++ b/src/main/java/shadowsocks/nio/tcp/ServerTcpWorker.java @@ -58,24 +58,24 @@ public class ServerTcpWorker extends TcpWorker { */ private void parseHeader() throws IOException, CryptoException, AuthException { - SocketChannel local = mSession.get(true); + SocketChannel local = mSession.getSocketChannel(true); ByteBuffer bb = BufferHelper.create(512); - mStreamUpData.reset(); + mStreamUpBuffer.reset(); // Read IV + address type length. - int len = mCryptor.getIVLength() + 1; + int len = mCrypto.getIVLength() + 1; BufferHelper.prepare(bb, len); local.read(bb); - byte [] result = mCryptor.decrypt(bb.array(), len); + byte [] result = mCrypto.decrypt(bb.array(), len); int addrtype = (int)(result[0] & 0xff); if ((addrtype & Session.OTA_FLAG) == Session.OTA_FLAG) { mOneTimeAuth = true; addrtype &= 0x0f; } - mStreamUpData.write(result[0]); + mStreamUpBuffer.write(result[0]); if (!mOneTimeAuth && mConfig.oneTimeAuth) { throw new AuthException("OTA is not enabled!"); @@ -87,22 +87,22 @@ private void parseHeader() throws IOException, CryptoException, AuthException //get IPV4 address BufferHelper.prepare(bb, 4); local.read(bb); - result = mCryptor.decrypt(bb.array(), 4); + result = mCrypto.decrypt(bb.array(), 4); addr = InetAddress.getByAddress(result); - mStreamUpData.write(result, 0, 4); + mStreamUpBuffer.write(result, 0, 4); }else if (addrtype == Session.ADDR_TYPE_HOST) { //get address len BufferHelper.prepare(bb, 1); local.read(bb); - result = mCryptor.decrypt(bb.array(), 1); + result = mCrypto.decrypt(bb.array(), 1); len = result[0]; - mStreamUpData.write(result[0]); + mStreamUpBuffer.write(result[0]); //get address BufferHelper.prepare(bb, len); local.read(bb); - result = mCryptor.decrypt(bb.array(), len); + result = mCrypto.decrypt(bb.array(), len); addr = InetAddress.getByName(new String(result, 0, len)); - mStreamUpData.write(result, 0, len); + mStreamUpBuffer.write(result, 0, len); } else { //do not support other addrtype now. throw new IOException("Unsupport addr type: " + addrtype + "!"); @@ -111,11 +111,11 @@ private void parseHeader() throws IOException, CryptoException, AuthException //get port BufferHelper.prepare(bb, 2); local.read(bb); - result = mCryptor.decrypt(bb.array(), 2); + result = mCrypto.decrypt(bb.array(), 2); BufferHelper.prepare(bb, 2); bb.put(result[0]); bb.put(result[1]); - mStreamUpData.write(result, 0, 2); + mStreamUpBuffer.write(result, 0, 2); // if port > 32767 the short will < 0 int port = (int)(bb.getShort(0)&0xFFFF); @@ -123,9 +123,9 @@ private void parseHeader() throws IOException, CryptoException, AuthException if (mOneTimeAuth){ BufferHelper.prepare(bb, HmacSHA1.AUTH_LEN); local.read(bb); - result = mCryptor.decrypt(bb.array(), HmacSHA1.AUTH_LEN); - byte [] authKey = SSAuth.prepareKey(mCryptor.getIV(false), mCryptor.getKey()); - byte [] authData = mStreamUpData.toByteArray(); + result = mCrypto.decrypt(bb.array(), HmacSHA1.AUTH_LEN); + byte [] authKey = SSAuth.prepareKey(mCrypto.getIV(false), mCrypto.getKey()); + byte [] authData = mStreamUpBuffer.toByteArray(); if (!mAuthor.doAuth(authKey, authData, result)){ throw new AuthException("Auth head failed"); } @@ -154,7 +154,7 @@ private boolean readAuthHead(SocketChannel sc) throws IOException,CryptoExceptio // Data len(2) + HMAC-SHA1 int authHeadLen = HmacSHA1.AUTH_LEN + 2; - byte [] result = mCryptor.decrypt(mAuthHeader.array(), authHeadLen); + byte [] result = mCrypto.decrypt(mAuthHeader.array(), authHeadLen); // Prepare for next chunck BufferHelper.prepare(mAuthHeader); @@ -172,7 +172,7 @@ private boolean readAuthHead(SocketChannel sc) throws IOException,CryptoExceptio // store the pre-calculated auth result System.arraycopy(result, 2, mExpectAuthResult, 0, HmacSHA1.AUTH_LEN); - mStreamUpData.reset(); + mStreamUpBuffer.reset(); return false; } @@ -199,17 +199,17 @@ protected boolean relay(SocketChannel source, SocketChannel target, int direct) byte [] result; if (direct == Session.LOCAL2REMOTE) { - result = mCryptor.decrypt(bb.array(), size); + result = mCrypto.decrypt(bb.array(), size); }else{ - result = mCryptor.encrypt(bb.array(), size); + result = mCrypto.encrypt(bb.array(), size); } if (mOneTimeAuth && direct == Session.LOCAL2REMOTE) { - mStreamUpData.write(result, 0, size); + mStreamUpBuffer.write(result, 0, size); mChunkLeft -= size; if (mChunkLeft == 0) { - byte [] authKey = SSAuth.prepareKey(mCryptor.getIV(false), mChunkCount); - byte [] authData = mStreamUpData.toByteArray(); + byte [] authKey = SSAuth.prepareKey(mCrypto.getIV(false), mChunkCount); + byte [] authData = mStreamUpBuffer.toByteArray(); if (!mAuthor.doAuth(authKey, authData, mExpectAuthResult)){ throw new AuthException("Auth chunk " + mChunkCount + " failed!"); } diff --git a/src/main/java/shadowsocks/nio/tcp/Session.java b/src/main/java/shadowsocks/nio/tcp/Session.java index 785c118..c6c5465 100644 --- a/src/main/java/shadowsocks/nio/tcp/Session.java +++ b/src/main/java/shadowsocks/nio/tcp/Session.java @@ -73,14 +73,14 @@ public boolean isTimeout() { return System.currentTimeMillis() - mLastActiveTime > mTimeout; } - public void set(SocketChannel sc, boolean isLocal) { + public void setSocketChannel(SocketChannel sc, boolean isLocal) { if (isLocal) mLocal = sc; else mRemote = sc; } - public SocketChannel get(boolean isLocal) { + public SocketChannel getSocketChannel(boolean isLocal) { return isLocal?mLocal:mRemote; } diff --git a/src/main/java/shadowsocks/nio/tcp/TcpWorker.java b/src/main/java/shadowsocks/nio/tcp/TcpWorker.java index 4feffc7..b7f23b7 100644 --- a/src/main/java/shadowsocks/nio/tcp/TcpWorker.java +++ b/src/main/java/shadowsocks/nio/tcp/TcpWorker.java @@ -69,12 +69,12 @@ public abstract class TcpWorker implements Runnable { private SocketChannel mLocal; protected Session mSession; - protected SSCrypto mCryptor; + protected SSCrypto mCrypto; protected LocalConfig mConfig; // For OTA // Store the data to do one time auth - protected ByteArrayOutputStream mStreamUpData; + protected ByteArrayOutputStream mStreamUpBuffer; protected boolean mOneTimeAuth = false; protected SSAuth mAuthor; protected int mChunkCount = 0; @@ -121,8 +121,8 @@ private void mainLoop(Selector selector, SocketChannel local, SocketChannel remo protected void TcpRelay() { int CONNECT_TIMEOUT = 5000; - SocketChannel remote = mSession.get(false); - SocketChannel local = mSession.get(true); + SocketChannel remote = mSession.getSocketChannel(false); + SocketChannel local = mSession.getSocketChannel(true); try(Selector selector = Selector.open()) { @@ -155,14 +155,14 @@ public void run(){ try(SocketChannel local = mLocal; SocketChannel remote = SocketChannel.open()) { mSession = new Session(); - mSession.set(local, true); - mSession.set(remote, false); + mSession.setSocketChannel(local, true); + mSession.setSocketChannel(remote, false); mSession.setTimeout(mConfig.timeout); // for decrypt/encrypt - mCryptor = CryptoFactory.create(mConfig.method, mConfig.password); + mCrypto = CryptoFactory.create(mConfig.method, mConfig.password); // for one time auth mAuthor = new HmacSHA1(); - mStreamUpData = new ByteArrayOutputStream(); + mStreamUpBuffer = new ByteArrayOutputStream(); TcpRelay(); }catch(Exception e){ log.error(e); diff --git a/src/main/java/shadowsocks/util/GlobalConfig.java b/src/main/java/shadowsocks/util/GlobalConfig.java index 8f3fea6..187d7ec 100644 --- a/src/main/java/shadowsocks/util/GlobalConfig.java +++ b/src/main/java/shadowsocks/util/GlobalConfig.java @@ -149,14 +149,14 @@ public synchronized static GlobalConfig get() public GlobalConfig() { - mMethod = new AtomicReference(DEFAULT_METHOD); - mPassword = new AtomicReference(DEFAULT_PASSWORD); - mServer = new AtomicReference(DEFAULT_SERVER); + mMethod = new AtomicReference(DEFAULT_METHOD); + mPassword = new AtomicReference(DEFAULT_PASSWORD); + mServer = new AtomicReference(DEFAULT_SERVER); mPort = new AtomicInteger(DEFAULT_PORT); mLocalPort = new AtomicInteger(DEFAULT_LOCAL_PORT); mOneTimeAuth = new AtomicBoolean(false); mIsServerMode = new AtomicBoolean(false); - mConfigFile = new AtomicReference(); + mConfigFile = new AtomicReference(); mTimeout = new AtomicInteger(DEFAULT_TIMEOUT); } @@ -206,7 +206,7 @@ public static void getConfigFromFile(){ } try{ int port = jsonobj.getInt("server_port"); - log.debug("CFG:Port: " + port); + log.debug("CFG:Server port: " + port); GlobalConfig.get().setPort(port); }catch(JSONException e){ //No this config, ignore; @@ -241,16 +241,23 @@ public static void getConfigFromFile(){ } try{ int timeout = jsonobj.getInt("timeout"); - log.debug("CFG:timeout: " + timeout); + log.debug("CFG:Timeout: " + timeout); GlobalConfig.get().setTimeout(timeout); }catch(JSONException e){ //No this config, ignore; } + try{ + boolean isServer = jsonobj.getBoolean("server_mode"); + log.debug("CFG:Running on server mode: " + isServer); + GlobalConfig.get().setServerMode(isServer); + }catch(JSONException e){ + //No this config, ignore; + } } - public static void getConfigFromArgv(String argv[]) + public static boolean getConfigFromArgv(String argv[]) { - Getopt g = new Getopt("shadowsocks", argv, "SLm:k:p:as:l:c:t:"); + Getopt g = new Getopt("shadowsocks", argv, "SLm:k:p:as:l:c:t:h"); int c; String arg; while ((c = g.getopt()) != -1) @@ -270,7 +277,7 @@ public static void getConfigFromArgv(String argv[]) case 'p': arg = g.getOptarg(); int port = Integer.parseInt(arg); - log.debug("CMD:Port: " + port); + log.debug("CMD:Server port: " + port); GlobalConfig.get().setPort(port); break; case 'a': @@ -307,12 +314,14 @@ public static void getConfigFromArgv(String argv[]) log.debug("CMD:timeout: " + timeout); GlobalConfig.get().setTimeout(timeout); break; + case 'h': case '?': default: help(); - break; + return false; } } + return true; } public static LocalConfig createLocalConfig() { @@ -332,6 +341,17 @@ public static LocalConfig createLocalConfig() { private static void help() { - //TODO + System.out.println("Usage:\n" + + " -m crypto method\n" + + " -k password\n" + + " -p bind port(server)/remote port(client)\n" + + " -a OTA enforcing mode\n" + + " -l local port\n" + + " -s server\n" + + " -S server mode\n" + + " -L Local mode(client, default)\n" + + " -c config file\n" + + " -t timeout(unit is second)\n" + + " -h show help.\n"); } } diff --git a/src/test/java/shadowsocks/UnitTest.java b/src/test/java/shadowsocks/UnitTest.java index 08676a4..4cf0e2a 100644 --- a/src/test/java/shadowsocks/UnitTest.java +++ b/src/test/java/shadowsocks/UnitTest.java @@ -77,7 +77,6 @@ public void testSetConfigFromFile() { //Start shadowsocks with config String [] argv = { "-c", fileName, - "-S", }; Main.main(argv); } catch(Exception e) { @@ -93,4 +92,12 @@ public void testSetConfigFromFile() { assertEquals(GlobalConfig.get().isOTAEnabled(), true); assertEquals(GlobalConfig.get().isServerMode(), true); } + + @Test + public void testHelp() { + String [] argv = { + "-h", + }; + Main.main(argv); + } } diff --git a/src/test/resources/demo-conf b/src/test/resources/demo-conf index 117bb80..695ae48 100644 --- a/src/test/resources/demo-conf +++ b/src/test/resources/demo-conf @@ -1,5 +1,6 @@ { "server":"fakeserver", + "server_mode":true, "server_port":1111, "local_port":2222, "password":"fakekey",