diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b63da45
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,42 @@
+.gradle
+build/
+!gradle/wrapper/gradle-wrapper.jar
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### IntelliJ IDEA ###
+.idea/modules.xml
+.idea/jarRepositories.xml
+.idea/compiler.xml
+.idea/libraries/
+*.iws
+*.iml
+*.ipr
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+
+### VS Code ###
+.vscode/
+
+### Mac OS ###
+.DS_Store
\ No newline at end of file
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..13566b8
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 0000000..7cecf2d
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
new file mode 100644
index 0000000..df543e3
--- /dev/null
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml
new file mode 100644
index 0000000..69e8615
--- /dev/null
+++ b/.idea/kotlinc.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..6aef776
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..dc20858
--- /dev/null
+++ b/README.md
@@ -0,0 +1,43 @@
+# vTunnel
+ポート解放をせずにVelocityプロキシへサーバーを登録できるトンネリングプラグインです。
+子サーバー起動時に自動的にVelocityプロキシへサーバーを登録します。(必要に応じてforcedHostsの登録も行います。)
+
+## セットアップする
+vTunnelのセットアップ方法。
+### プロキシサイドの設定
+1.vTunnelは子サーバーからのトンネリングの際に60000番ポートを使用するため、**60000番ポートを解放**する必要があります。
+また、解放する必要はありませんが60001-61000ポートを内部的に使用するため他プロセスで使用しないでください。(dockerでの実行を推奨)
+
+2.VelocityプロキシのpluginsフォルダにvTunnelプラグインを導入する
+3.下記のの環境変数を設定する
+(velocity-config.tomlのserversやtryの項目を削除することをお勧めします。)
+```yaml
+# JWTトークンのシークレットです。極力長い文字列にすることをお勧めします。
+VTUNNEL_SECRET: """任意のシークレット文字列""" (require)
+
+# サーバー接続時に最初に接続するサーバーの名前。
+VTUNNEL_TRY: "サーバー名1,サーバー名2" (optional)
+```
+### サーバーサイドの設定
+1.サーバーにvTunnelプラグインを導入します。
+2.JWTトークンを[ここ](https://jwt.io/)から生成する(下記参照)
+2.下記の環境変数を設定する
+#### JWTトークンの項目
+```yaml
+Algorithm: HS512
+
+your-256-bit-secret: """上で設定した$VTUNNEL_SECRETの値"""
+
+PAYLOAD:
+ name: lobby, #Velocityに登録するサーバー名
+ forced_hosts: ["lobby.example.com","main.example.com"], #Velocityに登録するforcedHostsのアドレス
+ exp: 1000000000000, #このトークンの有効期限(unix_time/sec)
+ iss: moruch4nn, #このトークンの発行者(適当で構いません)
+ aud: [サーバー運営], #このトークンの想定利用者(適当で構いません)
+```
+### 環境変数
+```yaml
+# vTunnelサーバーのホスト名
+VTUNNEL_HOST: 478.43.12.432
+VTUNNEL_TOKEN: 上で生成したJWTToken。
+```
\ No newline at end of file
diff --git a/client/build.gradle.kts b/client/build.gradle.kts
new file mode 100644
index 0000000..b953ba8
--- /dev/null
+++ b/client/build.gradle.kts
@@ -0,0 +1,32 @@
+plugins {
+ id("com.github.johnrengelman.shadow") version "7.1.2"
+ kotlin("jvm") version "1.8.20"
+ kotlin("plugin.serialization") version "1.8.20"
+}
+
+group = "dev.mr3n"
+version = "1.0-SNAPSHOT"
+
+repositories {
+ maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/")
+ maven("https://oss.sonatype.org/content/repositories/snapshots")
+ mavenCentral()
+}
+
+dependencies {
+ compileOnly("org.spigotmc:spigot-api:1.8-R0.1-SNAPSHOT")
+ implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
+ implementation("com.auth0:java-jwt:4.4.0")
+ implementation("io.ktor:ktor-client-core:2.2.4")
+ implementation("io.ktor:ktor-serialization-kotlinx-json:2.2.4")
+ implementation("io.ktor:ktor-client-cio:2.2.4")
+ implementation(project(":shared"))
+}
+
+tasks.named("build") {
+ dependsOn("shadowJar")
+}
+
+kotlin {
+ jvmToolchain(8)
+}
\ No newline at end of file
diff --git a/client/src/main/kotlin/dev/mr3n/vtunnel/VTunnel.kt b/client/src/main/kotlin/dev/mr3n/vtunnel/VTunnel.kt
new file mode 100644
index 0000000..f8974e2
--- /dev/null
+++ b/client/src/main/kotlin/dev/mr3n/vtunnel/VTunnel.kt
@@ -0,0 +1,68 @@
+package dev.mr3n.vtunnel
+
+import dev.mr3n.vtunnel.model.AuthFrame
+import dev.mr3n.vtunnel.model.NewConnectionNotify
+import dev.mr3n.vtunnel.tcp.PacketTransfer
+import io.ktor.client.*
+import io.ktor.client.engine.cio.*
+import io.ktor.client.plugins.websocket.*
+import io.ktor.serialization.kotlinx.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import org.bukkit.Bukkit
+import org.bukkit.event.EventHandler
+import org.bukkit.event.EventPriority
+import org.bukkit.event.Listener
+import org.bukkit.event.player.PlayerLoginEvent
+import org.bukkit.plugin.java.JavaPlugin
+import java.net.Socket
+import java.util.*
+import kotlin.concurrent.thread
+
+class VTunnel: JavaPlugin(), Listener {
+
+ init {
+ Bukkit.getServer().onlineMode
+ }
+
+ override fun onEnable() {
+ thread { runBlocking { startWebSocketClient() } }
+ this.server.pluginManager.registerEvents(this, this)
+ }
+
+ val client = HttpClient(CIO) {
+ install(WebSockets) {
+ contentConverter = KotlinxWebsocketSerializationConverter(Json)
+ }
+ }
+
+ suspend fun startWebSocketClient() {
+ val host = System.getenv("VTUNNEL_HOST")?:"akamachi.net"
+ val token = System.getenv("VTUNNEL_TOKEN")
+ while (true) {
+ try {
+ client.webSocket(host = host, port = 60000, path = "/vtunnel") {
+ sendSerialized(AuthFrame(token))
+ while (true) {
+ val newConn: NewConnectionNotify = receiveDeserialized()
+ try {
+ val bridgeSocket = Socket(host, newConn.port)
+ val outputSocket = bridgeSocket.getOutputStream()
+ outputSocket.write(Json.encodeToString(AuthFrame(newConn.token)).toByteArray())
+ outputSocket.flush()
+ val clientSocket = Socket("127.0.0.1", server.port)
+ PacketTransfer(bridgeSocket, clientSocket)
+ } catch (e: Exception) {
+ e.printStackTrace()
+ }
+ }
+ }
+ } catch (e: Exception) {
+ e.printStackTrace()
+ }
+ logger.warning("vTunnelとの接続が切断されたため5秒後に再接続を行います。")
+ Thread.sleep(5000)
+ }
+ }
+}
\ No newline at end of file
diff --git a/client/src/main/resources/plugin.yml b/client/src/main/resources/plugin.yml
new file mode 100644
index 0000000..0cedded
--- /dev/null
+++ b/client/src/main/resources/plugin.yml
@@ -0,0 +1,3 @@
+main: dev.mr3n.vtunnel.VTunnel
+name: VTunnel
+version: 1.0
\ No newline at end of file
diff --git a/client/src/main/resources/test b/client/src/main/resources/test
new file mode 100644
index 0000000..92be82c
--- /dev/null
+++ b/client/src/main/resources/test
@@ -0,0 +1 @@
+2023-04-21 10:45:47 [01:45:47 INFO]: [long, class net.minecraft.server.network.PlayerConnection, class net.minecraft.server.MinecraftServer, class net.minecraft.server.level.PlayerInteractManager, int, int, boolean, boolean, class net.minecraft.world.entity.monster.warden.WardenSpawnTracker, interface net.minecraft.world.inventory.ContainerSynchronizer, int, boolean, long, int, boolean, class net.minecraft.network.protocol.game.PacketPlayOutUpdateHealth, int, class [I, class com.destroystokyo.paper.util.PooledHashSets$PooledObjectLinkedOpenHashSet, class java.lang.String, interface net.kyori.adventure.text.Component, interface net.minecraft.network.chat.IChatBaseComponent, class org.bukkit.Location, int, int, int, boolean, double, boolean, boolean, boolean, class java.lang.Integer, boolean, double, class com.destroystokyo.paper.util.misc.PooledLinkedHashSets$PooledObjectLinkedOpenHashSet, class com.destroystokyo.paper.event.entity.PlayerNaturallySpawnCreaturesEvent, class org.bukkit.event.player.PlayerQuitEvent$QuitReason, class java.lang.String, class java.util.Locale, long, boolean, class org.bukkit.WeatherType, int, int, int, int, int, float, float, float, float, class net.minecraft.world.entity.EntitySize, class net.minecraft.network.syncher.DataWatcherObject, class net.minecraft.world.inventory.ContainerPlayer, class net.minecraft.world.inventory.Container, float, float, int, double, double, double, double, double, double, int, int, int, float, int, class com.mojang.authlib.GameProfile, class net.minecraft.world.entity.projectile.EntityFishingHook, float, boolean, class net.kyori.adventure.util.TriState, boolean, int, int, int, int, int, int, int, double, double, int, int, class net.minecraft.network.syncher.DataWatcherObject, class net.minecraft.network.syncher.DataWatcherObject, float, class net.minecraft.world.damagesource.CombatTracker, interface java.util.Map, boolean, class net.minecraft.world.EnumHand, int, int, int, int, int, int, float, float, class net.minecraft.world.entity.WalkAnimationState, int, float, float, float, float, float, float, class net.minecraft.world.entity.player.EntityHuman, int, float, boolean, float, float, float, boolean, class net.minecraft.world.entity.EntityLiving, int, int, boolean, class java.util.ArrayList, class org.bukkit.craftbukkit.v1_19_R3.attribute.CraftAttributeMap, boolean, interface java.util.Set, boolean, boolean, class net.kyori.adventure.util.TriState, int, boolean, interface net.minecraft.util.RandomSource, class org.bukkit.event.entity.CreatureSpawnEvent$SpawnReason, class com.destroystokyo.paper.loottable.PaperLootableInventoryData, boolean, class net.minecraft.server.level.PlayerChunkMap$EntityTracker, class java.lang.Throwable, class java.lang.String, class java.lang.String, int, int, int, double, float, int, int, class java.lang.String, boolean, class com.google.common.collect.ImmutableList, class net.minecraft.world.level.World, double, double, double, float, float, boolean, boolean, boolean, boolean, boolean, boolean, float, float, float, float, float, float, float, double, double, double, boolean, int, int, boolean, int, boolean, boolean, int, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, int, interface org.bukkit.projectiles.ProjectileSource, boolean, boolean, class net.minecraft.core.BlockPosition, class org.spigotmc.ActivationRange$ActivationType, boolean, long, long, boolean, boolean, boolean, boolean, boolean, class net.minecraft.server.level.PlayerChunk$State, int, int, int, boolean, boolean, class net.minecraft.core.BlockPosition, class net.minecraft.server.level.WorldServer, class java.lang.Object, interface net.minecraft.commands.ICommandListener]
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..7fc6f1f
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1 @@
+kotlin.code.style=official
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..249e583
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..60c76b3
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
\ No newline at end of file
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..1b6c787
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,234 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed 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
+#
+# https://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.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${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='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# 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 ;; #(
+ MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..ac1b06f
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,89 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@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 Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@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="-Xmx64m" "-Xms64m"
+
+@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 execute
+
+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 execute
+
+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
+
+: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 %*
+
+: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/server/build.gradle.kts b/server/build.gradle.kts
new file mode 100644
index 0000000..84aed73
--- /dev/null
+++ b/server/build.gradle.kts
@@ -0,0 +1,31 @@
+plugins {
+ id("com.github.johnrengelman.shadow") version "7.1.2"
+ kotlin("jvm") version "1.8.20"
+ kotlin("plugin.serialization") version "1.8.20"
+}
+
+group = "dev.mr3n"
+version = "1.0-SNAPSHOT"
+
+repositories {
+ mavenCentral()
+ maven("https://repo.papermc.io/repository/maven-public/")
+}
+
+dependencies {
+ implementation("io.ktor:ktor-serialization-kotlinx-json:2.2.4")
+ implementation("io.ktor:ktor-server-core:2.2.4")
+ implementation("io.ktor:ktor-server-websockets:2.2.4")
+ implementation("io.ktor:ktor-server-netty:2.2.4")
+ implementation("com.velocitypowered:velocity-api:3.1.1")
+ implementation("com.auth0:java-jwt:4.4.0")
+ implementation(project(":shared"))
+}
+
+tasks.named("build") {
+ dependsOn("shadowJar")
+}
+
+kotlin {
+ jvmToolchain(8)
+}
\ No newline at end of file
diff --git a/server/src/main/kotlin/dev/mr3n/vtunnel/VTunnel.kt b/server/src/main/kotlin/dev/mr3n/vtunnel/VTunnel.kt
new file mode 100644
index 0000000..562f9f7
--- /dev/null
+++ b/server/src/main/kotlin/dev/mr3n/vtunnel/VTunnel.kt
@@ -0,0 +1,66 @@
+package dev.mr3n.vtunnel
+
+import com.velocitypowered.api.event.Subscribe
+import com.velocitypowered.api.event.connection.ConnectionHandshakeEvent
+import com.velocitypowered.api.event.connection.LoginEvent
+import com.velocitypowered.api.event.connection.PreLoginEvent
+import com.velocitypowered.api.event.player.KickedFromServerEvent
+import com.velocitypowered.api.event.player.PlayerChooseInitialServerEvent
+import com.velocitypowered.api.event.player.ServerPreConnectEvent
+import com.velocitypowered.api.event.proxy.ProxyInitializeEvent
+import com.velocitypowered.api.event.proxy.ProxyPingEvent
+import com.velocitypowered.api.plugin.Plugin
+import com.velocitypowered.api.proxy.ProxyServer
+import com.velocitypowered.api.proxy.server.RegisteredServer
+import dev.mr3n.vtunnel.tunnel.startTunnelingAllocator
+import net.kyori.adventure.text.Component
+import org.w3c.dom.Text
+import java.net.InetSocketAddress
+import java.util.*
+import java.util.logging.Logger
+import javax.inject.Inject
+import kotlin.concurrent.thread
+import kotlin.jvm.optionals.getOrNull
+
+@Plugin(id = "vtunnel")
+class VTunnel @Inject constructor(val server: ProxyServer, val logger: Logger) {
+ @Subscribe
+ fun on(event: ProxyInitializeEvent) {
+ thread { startTunnelingAllocator() }
+ }
+
+ @Subscribe
+ fun on(event: PlayerChooseInitialServerEvent) {
+ val virtualHostStr = event.player.virtualHost.map(InetSocketAddress::getHostString).orElse("").lowercase(Locale.ROOT)
+ (customForcedHosts[virtualHostStr]?:tryServer())?.let(event::setInitialServer)
+ }
+
+ @Subscribe
+ fun on(event: KickedFromServerEvent) {
+ val server = tryServer(event.server.serverInfo.name)
+ event.result = KickedFromServerEvent.RedirectPlayer.create(server)
+ }
+
+ init {
+ SERVER = server
+ LOGGER = logger
+ }
+
+ companion object {
+ lateinit var SERVER: ProxyServer
+ lateinit var LOGGER: Logger
+
+ val customForcedHosts = mutableMapOf()
+ private val tryFirst = System.getenv("VTUNNEL_TRY")?.split(",")?:listOf()
+
+ fun tryServer(vararg ignore: String): RegisteredServer? {
+ val formattedIgnore = ignore.map { it.lowercase() }
+ tryFirst.map(SERVER::getServer)
+ .mapNotNull(Optional::getOrNull)
+ .forEach { server ->
+ if(formattedIgnore.contains(server.serverInfo.name.lowercase())) { return@forEach }
+ return server }
+ return null
+ }
+ }
+}
\ No newline at end of file
diff --git a/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/PortManager.kt b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/PortManager.kt
new file mode 100644
index 0000000..b7c182a
--- /dev/null
+++ b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/PortManager.kt
@@ -0,0 +1,15 @@
+package dev.mr3n.vtunnel.tunnel
+
+object PortManager {
+ private val ports = (60002..61000)
+
+ private val usingPorts = mutableListOf()
+
+ fun port(): Int {
+ var port: Int
+ do { port = ports.random() } while (port in usingPorts)
+ return port
+ }
+
+ fun free(port: Int) = usingPorts.remove(port)
+}
\ No newline at end of file
diff --git a/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/TunnelAllocator.kt b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/TunnelAllocator.kt
new file mode 100644
index 0000000..781a565
--- /dev/null
+++ b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/TunnelAllocator.kt
@@ -0,0 +1,84 @@
+package dev.mr3n.vtunnel.tunnel
+
+import com.auth0.jwt.JWT
+import com.auth0.jwt.algorithms.Algorithm
+import com.velocitypowered.api.proxy.server.ServerInfo
+import dev.mr3n.vtunnel.VTunnel
+import dev.mr3n.vtunnel.model.AuthFrame
+import dev.mr3n.vtunnel.model.InitAuthModel
+import dev.mr3n.vtunnel.tunnel.tcp.BridgeNotifierConnection
+import io.ktor.serialization.kotlinx.*
+import io.ktor.server.application.*
+import io.ktor.server.engine.*
+import io.ktor.server.netty.*
+import io.ktor.server.routing.*
+import io.ktor.server.websocket.*
+import io.ktor.websocket.*
+import kotlinx.serialization.json.Json
+import java.net.InetSocketAddress
+import java.time.Duration
+import java.util.*
+import kotlin.collections.LinkedHashMap
+import kotlin.jvm.optionals.getOrNull
+
+val connections = Collections.synchronizedMap(LinkedHashMap())
+
+
+val algorithm = Algorithm.HMAC512(System.getenv("VTUNNEL_SECRET"))
+val verifier = JWT.require(algorithm).acceptExpiresAt(5).build()
+
+private fun Routing.setupWebSocket() {
+ webSocket("/vtunnel") {
+ try {
+ val authInfo: AuthFrame = receiveDeserialized()
+ val jwt = verifier.verify(authInfo.token)
+ val initAuth = InitAuthModel(jwt)
+ val serverName = initAuth.name
+ if(connections.containsKey(serverName)) { return@webSocket close() }
+ val forcedHosts = initAuth.forcedHosts
+
+ val thisConnection = BridgeNotifierConnection(this)
+
+ VTunnel.SERVER.getServer(serverName)?.getOrNull()?.serverInfo?.let(VTunnel.SERVER::unregisterServer)
+ val info = ServerInfo(serverName, InetSocketAddress("localhost",thisConnection.publicPort))
+ val registeredServer = VTunnel.SERVER.registerServer(info)
+ forcedHosts.forEach { VTunnel.customForcedHosts[it] = registeredServer }
+
+ try {
+ connections[initAuth.name] = thisConnection
+
+ VTunnel.LOGGER.info("${serverName}との新しいブリッジコネクションを確立しました。")
+
+ for (frame in incoming) { }
+
+ } catch (e: Exception) {
+ e.printStackTrace()
+ } finally {
+ VTunnel.LOGGER.info("${initAuth.name}とのブリッジコネクションが切断されました。")
+
+ forcedHosts.forEach(VTunnel.customForcedHosts::remove)
+ VTunnel.SERVER.unregisterServer(info)
+
+ connections.remove(initAuth.name)
+ }
+ } catch (_: Exception) { }
+ }
+}
+
+fun startTunnelingAllocator() {
+ embeddedServer(
+ factory = Netty,
+ port = 60000,
+ host = "0.0.0.0",
+ module = {
+ install(WebSockets) {
+ pingPeriod = Duration.ofSeconds(15)
+ timeout = Duration.ofSeconds(15)
+ maxFrameSize = Long.MAX_VALUE
+ masking = false
+ contentConverter = KotlinxWebsocketSerializationConverter(Json)
+ }
+ routing { this.setupWebSocket() }
+ }
+ ).start(true)
+}
\ No newline at end of file
diff --git a/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/BridgeConnection.kt b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/BridgeConnection.kt
new file mode 100644
index 0000000..a62101a
--- /dev/null
+++ b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/BridgeConnection.kt
@@ -0,0 +1,51 @@
+package dev.mr3n.vtunnel.tunnel.tcp
+
+import com.auth0.jwt.JWT
+import dev.mr3n.vtunnel.model.AuthFrame
+import dev.mr3n.vtunnel.model.TCPAuthModel
+import kotlinx.serialization.decodeFromString
+import kotlinx.serialization.json.Json
+import java.net.ServerSocket
+import java.net.Socket
+import java.util.Base64
+import java.util.Timer
+import java.util.UUID
+import java.util.concurrent.CopyOnWriteArrayList
+import kotlin.concurrent.schedule
+import kotlin.concurrent.thread
+
+object BridgeConnection {
+ val port = 60001
+ val serverSocket = ServerSocket(port)
+
+ private val timer = Timer()
+
+ private val base64Encoder = Base64.getEncoder()
+
+ private val waitCons = CopyOnWriteArrayList()
+
+ fun wait(con: (Socket)->Unit): String {
+ val id = base64Encoder.encode("${UUID.randomUUID()}${UUID.randomUUID()}".encodeToByteArray()).decodeToString()
+ val info = WaitConnectionInfo(con, id, System.currentTimeMillis())
+ this.waitCons.add(info)
+ timer.schedule(1000 * 10) { this@BridgeConnection.waitCons.remove(info) }
+ return id
+ }
+
+ val thread = thread {
+ while (true) {
+ val socket = serverSocket.accept()
+ try {
+ val buffer = ByteArray(60000)
+ val len = socket.getInputStream().read(buffer)
+ if(len == -1) { continue }
+ val authInfo = TCPAuthModel(JWT.decode(Json.decodeFromString(String(buffer, 0, len)).token))
+
+ val info = waitCons.find { it.id == authInfo.id }?:continue
+ info.run(socket)
+ } catch (e: Exception) {
+ e.printStackTrace()
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/BridgeNotifierConnection.kt b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/BridgeNotifierConnection.kt
new file mode 100644
index 0000000..069d78f
--- /dev/null
+++ b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/BridgeNotifierConnection.kt
@@ -0,0 +1,44 @@
+package dev.mr3n.vtunnel.tunnel.tcp
+
+import com.auth0.jwt.JWT
+import com.velocitypowered.api.proxy.server.ServerInfo
+import dev.mr3n.vtunnel.VTunnel
+import dev.mr3n.vtunnel.model.NewConnectionNotify
+import dev.mr3n.vtunnel.tcp.PacketTransfer
+import dev.mr3n.vtunnel.tunnel.PortManager
+import dev.mr3n.vtunnel.tunnel.algorithm
+import io.ktor.server.websocket.*
+import kotlinx.coroutines.runBlocking
+import java.net.InetSocketAddress
+import java.net.ServerSocket
+import java.util.concurrent.CopyOnWriteArraySet
+import kotlin.jvm.optionals.getOrNull
+
+class BridgeNotifierConnection(val webSocketServerSession: DefaultWebSocketServerSession): Thread() {
+ val publicPort = PortManager.port()
+ private val public = ServerSocket(publicPort)
+
+ private val transfers = CopyOnWriteArraySet()
+
+ override fun run() {
+ while(true) {
+ val socket1 = public.accept()
+ try {
+ val id = BridgeConnection.wait { socket2 ->
+ val packetTransfer = PacketTransfer(socket1,socket2)
+ transfers.add(packetTransfer)
+
+ packetTransfer.closeProcess { this.transfers.remove(packetTransfer) }
+ packetTransfer.closeProcess { PortManager.free(publicPort) }
+ }
+
+ val token = JWT.create().withClaim("id", id).sign(algorithm)
+ runBlocking { webSocketServerSession.sendSerialized(NewConnectionNotify(BridgeConnection.port,token)) }
+ } catch (e: Exception) {
+ e.printStackTrace()
+ }
+ }
+ }
+
+ init { this.start() }
+}
\ No newline at end of file
diff --git a/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/WaitConnectionInfo.kt b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/WaitConnectionInfo.kt
new file mode 100644
index 0000000..fda6ea4
--- /dev/null
+++ b/server/src/main/kotlin/dev/mr3n/vtunnel/tunnel/tcp/WaitConnectionInfo.kt
@@ -0,0 +1,5 @@
+package dev.mr3n.vtunnel.tunnel.tcp
+
+import java.net.Socket
+
+class WaitConnectionInfo(val run: (Socket)->Unit, val id: String, val createdAt: Long = System.currentTimeMillis())
\ No newline at end of file
diff --git a/server/src/main/resources/velocity-plugin.json b/server/src/main/resources/velocity-plugin.json
new file mode 100644
index 0000000..c76fc6c
--- /dev/null
+++ b/server/src/main/resources/velocity-plugin.json
@@ -0,0 +1,5 @@
+{
+ "main": "dev.mr3n.vtunnel.VTunnel",
+ "id": "vtunnel",
+ "version": "1.0"
+}
\ No newline at end of file
diff --git a/settings.gradle.kts b/settings.gradle.kts
new file mode 100644
index 0000000..61ed6d9
--- /dev/null
+++ b/settings.gradle.kts
@@ -0,0 +1,4 @@
+
+rootProject.name = "vTunnel"
+
+include("shared", "server", "client")
\ No newline at end of file
diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts
new file mode 100644
index 0000000..e08965b
--- /dev/null
+++ b/shared/build.gradle.kts
@@ -0,0 +1,27 @@
+plugins {
+ kotlin("jvm") version "1.8.20"
+ kotlin("plugin.serialization") version "1.8.20"
+ id("com.github.johnrengelman.shadow") version "7.1.2"
+}
+
+group = "dev.mr3n"
+version = "1.0-SNAPSHOT"
+
+repositories {
+ mavenCentral()
+ maven("https://repo.papermc.io/repository/maven-public/")
+}
+
+dependencies {
+ implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
+ implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
+ implementation("com.auth0:java-jwt:4.4.0")
+}
+
+tasks.named("build") {
+ dependsOn("shadowJar")
+}
+
+kotlin {
+ jvmToolchain(8)
+}
\ No newline at end of file
diff --git a/shared/src/main/kotlin/dev/mr3n/vtunnel/model/AuthFrame.kt b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/AuthFrame.kt
new file mode 100644
index 0000000..b8548c1
--- /dev/null
+++ b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/AuthFrame.kt
@@ -0,0 +1,6 @@
+package dev.mr3n.vtunnel.model
+
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class AuthFrame(val token: String)
\ No newline at end of file
diff --git a/shared/src/main/kotlin/dev/mr3n/vtunnel/model/InitAuthModel.kt b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/InitAuthModel.kt
new file mode 100644
index 0000000..965549e
--- /dev/null
+++ b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/InitAuthModel.kt
@@ -0,0 +1,18 @@
+package dev.mr3n.vtunnel.model
+
+import com.auth0.jwt.interfaces.DecodedJWT
+import kotlinx.datetime.Instant
+import kotlinx.datetime.toKotlinInstant
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class InitAuthModel(
+ val name: String,
+ @SerialName("forced_hosts")
+ val forcedHosts: List,
+ val iss: String,
+ val exp: Instant,
+ val aud: List) {
+ constructor(jwt: DecodedJWT): this(jwt.getClaim("name").asString(), jwt.getClaim("forced_hosts").asList(String::class.java),jwt.issuer,jwt.expiresAtAsInstant.toKotlinInstant(),jwt.audience)
+}
\ No newline at end of file
diff --git a/shared/src/main/kotlin/dev/mr3n/vtunnel/model/NewConnectionNotify.kt b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/NewConnectionNotify.kt
new file mode 100644
index 0000000..acb4fef
--- /dev/null
+++ b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/NewConnectionNotify.kt
@@ -0,0 +1,6 @@
+package dev.mr3n.vtunnel.model
+
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class NewConnectionNotify(val port: Int, val token: String)
diff --git a/shared/src/main/kotlin/dev/mr3n/vtunnel/model/TCPAuthModel.kt b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/TCPAuthModel.kt
new file mode 100644
index 0000000..598ef1a
--- /dev/null
+++ b/shared/src/main/kotlin/dev/mr3n/vtunnel/model/TCPAuthModel.kt
@@ -0,0 +1,7 @@
+package dev.mr3n.vtunnel.model
+
+import com.auth0.jwt.interfaces.DecodedJWT
+
+data class TCPAuthModel(val id: String) {
+ constructor(jwt: DecodedJWT): this(jwt.getClaim("id").asString())
+}
\ No newline at end of file
diff --git a/shared/src/main/kotlin/dev/mr3n/vtunnel/tcp/PacketTransfer.kt b/shared/src/main/kotlin/dev/mr3n/vtunnel/tcp/PacketTransfer.kt
new file mode 100644
index 0000000..6bae9e1
--- /dev/null
+++ b/shared/src/main/kotlin/dev/mr3n/vtunnel/tcp/PacketTransfer.kt
@@ -0,0 +1,43 @@
+package dev.mr3n.vtunnel.tcp
+
+import java.io.Closeable
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.Socket
+import java.util.concurrent.CopyOnWriteArraySet
+import kotlin.concurrent.thread
+
+class PacketTransfer(private val socket1: Socket, private val socket2: Socket): Closeable {
+ private val streams = CopyOnWriteArraySet()
+ var isClosed = false
+ private val closeProcesses = CopyOnWriteArraySet<()->Unit>()
+ val thread1 = thread {
+ this.transfer(socket1.getInputStream(),socket2.getOutputStream())
+ }
+ val thread2 = thread {
+ this.transfer(socket2.getInputStream(),socket1.getOutputStream())
+ }
+ private fun transfer(inputStream: InputStream, outputStream: OutputStream) {
+ this.streams.add(inputStream)
+ this.streams.add(outputStream)
+ val buffer = ByteArray(60000)
+ while (true) {
+ try {
+ val len = inputStream.read(buffer)
+ if(len == -1) { break }
+ outputStream.write(buffer,0,len)
+ outputStream.flush()
+ } catch (_: Exception) { break }
+ }
+ this.close()
+ }
+ fun closeProcess(process: ()->Unit) { this.closeProcesses.add(process) }
+ override fun close() {
+ if(this.isClosed) { return }
+ this.isClosed = true
+ this.streams.forEach(Closeable::close)
+ if(socket1.isClosed) { this.socket1.close() }
+ if(socket2.isClosed) { this.socket2.close() }
+ this.closeProcesses.forEach { it.invoke() }
+ }
+}
\ No newline at end of file