Search in sources :

Example 1 with Event

use of org.spongepowered.api.event.Event in project guardian by ichorpowered.

the class CorePluginFacet method startup.

public Boolean startup(SimpleFacetMessage componentMessage) {
    this.facetState = FacetState.PREPARE;
    SimpleGuardian.setInstance(this.plugin);
    PropertyInjector propertyInjector = this.plugin.getPropertyInjector();
    propertyInjector.inject("state", GuardianState.PRE_INITIALIZATION);
    // STATE: PRE_INITIALIZATION
    if (PluginInfo.EXPERIMENTAL) {
        this.logger.warn(ConsoleUtil.of(Ansi.Color.RED, "You are using an experimental build of Guardian."));
        this.logger.warn(ConsoleUtil.of(Ansi.Color.RED, "This may not be ready for a production environment. Use at your own risk!"));
    }
    this.logger.info(ConsoleUtil.of("Guardian v{} for Sponge {} and Minecraft {}", PluginInfo.VERSION, Sponge.getPlatform().getContainer(Platform.Component.API).getVersion().map(version -> version.substring(0, 5)).orElse("?"), Sponge.getPlatform().getContainer(Platform.Component.GAME).getVersion().orElse("?")));
    Sponge.getServiceManager().setProvider(this.plugin, AntiCheatService.class, new GuardianBypassService(this.plugin));
    ModuleController<GuardianPlugin> moduleController = ShadedModularFramework.registerModuleController(this.plugin, Sponge.getGame());
    SimpleEventBus<GuardianEvent, GuardianListener> eventBus = new SimpleEventBus<>(new ASMEventExecutorFactory<GuardianEvent, GuardianListener>());
    this.logger.info(ConsoleUtil.of("Loaded pre-facet systems: { me4502/modularframework v1.8.5, kyoripowered/event v1.0.0 }"));
    // PROVIDE: PRE_INITIALIZATION
    propertyInjector.inject("coreTime", componentMessage.getTime());
    propertyInjector.inject("moduleController", moduleController);
    propertyInjector.inject("eventBus", eventBus);
    this.plugin.getEventBus().post(new GuardianPreInitializationEvent(Origin.source(this.plugin.getPluginContainer()).build()));
    propertyInjector.inject("state", GuardianState.INITIALIZATION);
    // State: INITIALIZATION
    this.logger.info(this.facetPrefix + "Initializing storage.");
    Configuration configuration = new Configuration(this.plugin, this.plugin.getConfigDirectory());
    configuration.load();
    this.logger.info(this.facetPrefix + "Initializing registries.");
    InternalBypassService internalBypassService = new InternalBypassService(this.plugin);
    GuardianDetectionManager detectionManager = new GuardianDetectionManager(this.plugin);
    SequenceRegistry<Event> sequenceRegistry = new SequenceRegistry<>();
    this.logger.info(this.facetPrefix + "Initializing systems.");
    GuardianSequenceManager sequenceManager = new GuardianSequenceManager(this.plugin, sequenceRegistry);
    GuardianSequenceManager.SequenceTask sequenceTask = new GuardianSequenceManager.SequenceTask(this.plugin, sequenceManager);
    GuardianSequenceListener sequenceListener = new GuardianSequenceListener(this.plugin);
    Common common = new Common(this.plugin);
    GuardianContentKeys contentKeys = new GuardianContentKeys();
    contentKeys.createKeys();
    // PROVIDE: INITIALIZATION
    propertyInjector.inject("common", common);
    propertyInjector.inject("configuration", configuration);
    propertyInjector.inject("internalBypassService", internalBypassService);
    propertyInjector.inject("detectionManager", detectionManager);
    propertyInjector.inject("sequenceManager", sequenceManager);
    propertyInjector.inject("sequenceTask", sequenceTask);
    propertyInjector.inject("sequenceRegistry", sequenceRegistry);
    propertyInjector.inject("sequenceListener", sequenceListener);
    this.plugin.getEventBus().post(new GuardianInitializationEvent(Origin.source(this.plugin.getPluginContainer()).build()));
    this.facetState = FacetState.START;
    return true;
}
Also used : Ansi(org.fusesource.jansi.Ansi) FacetMessage(com.ichorpowered.guardian.launch.message.FacetMessage) AntiCheatService(com.me4502.precogs.service.AntiCheatService) SimpleEventBus(net.kyori.event.SimpleEventBus) SimpleFacetMessage(com.ichorpowered.guardian.launch.message.SimpleFacetMessage) GuardianSequenceListener(com.ichorpowered.guardian.sequence.GuardianSequenceListener) ASMEventExecutorFactory(net.kyori.event.ASMEventExecutorFactory) GuardianPlugin(com.ichorpowered.guardian.GuardianPlugin) GuardianListener(com.ichorpowered.guardianapi.event.GuardianListener) PluginInfo(com.ichorpowered.guardian.PluginInfo) Platform(org.spongepowered.api.Platform) Origin(com.ichorpowered.guardianapi.event.origin.Origin) InternalBypassService(com.ichorpowered.guardian.service.InternalBypassService) Common(com.ichorpowered.guardian.Common) GuardianInitializationEvent(com.ichorpowered.guardian.event.GuardianInitializationEvent) GuardianSequenceManager(com.ichorpowered.guardian.sequence.GuardianSequenceManager) FacetState(com.ichorpowered.guardian.launch.FacetState) GuardianState(com.ichorpowered.guardianapi.GuardianState) GuardianBypassService(com.ichorpowered.guardian.service.GuardianBypassService) PropertyInjector(com.ichorpowered.guardian.util.property.PropertyInjector) Configuration(com.ichorpowered.guardian.Configuration) SequenceRegistry(com.abilityapi.sequenceapi.SequenceRegistry) FacetBootstrap(com.ichorpowered.guardian.launch.FacetBootstrap) SimpleGuardian(com.ichorpowered.guardianapi.SimpleGuardian) Logger(org.slf4j.Logger) GuardianDetectionManager(com.ichorpowered.guardian.detection.GuardianDetectionManager) Event(org.spongepowered.api.event.Event) ConsoleUtil(com.ichorpowered.guardian.util.ConsoleUtil) Sponge(org.spongepowered.api.Sponge) GuardianEvent(com.ichorpowered.guardianapi.event.GuardianEvent) Facet(com.ichorpowered.guardian.launch.Facet) GuardianPreInitializationEvent(com.ichorpowered.guardian.event.GuardianPreInitializationEvent) ModuleController(com.me4502.modularframework.ModuleController) GuardianContentKeys(com.ichorpowered.guardian.content.GuardianContentKeys) FacetException(com.ichorpowered.guardian.launch.exception.FacetException) ShadedModularFramework(com.me4502.modularframework.ShadedModularFramework) InternalBypassService(com.ichorpowered.guardian.service.InternalBypassService) Configuration(com.ichorpowered.guardian.Configuration) SequenceRegistry(com.abilityapi.sequenceapi.SequenceRegistry) GuardianEvent(com.ichorpowered.guardianapi.event.GuardianEvent) GuardianListener(com.ichorpowered.guardianapi.event.GuardianListener) GuardianContentKeys(com.ichorpowered.guardian.content.GuardianContentKeys) GuardianPreInitializationEvent(com.ichorpowered.guardian.event.GuardianPreInitializationEvent) GuardianSequenceManager(com.ichorpowered.guardian.sequence.GuardianSequenceManager) Common(com.ichorpowered.guardian.Common) PropertyInjector(com.ichorpowered.guardian.util.property.PropertyInjector) GuardianBypassService(com.ichorpowered.guardian.service.GuardianBypassService) SimpleEventBus(net.kyori.event.SimpleEventBus) GuardianInitializationEvent(com.ichorpowered.guardian.event.GuardianInitializationEvent) Event(org.spongepowered.api.event.Event) GuardianEvent(com.ichorpowered.guardianapi.event.GuardianEvent) GuardianPreInitializationEvent(com.ichorpowered.guardian.event.GuardianPreInitializationEvent) GuardianDetectionManager(com.ichorpowered.guardian.detection.GuardianDetectionManager) GuardianSequenceListener(com.ichorpowered.guardian.sequence.GuardianSequenceListener) GuardianPlugin(com.ichorpowered.guardian.GuardianPlugin) GuardianInitializationEvent(com.ichorpowered.guardian.event.GuardianInitializationEvent)

Example 2 with Event

use of org.spongepowered.api.event.Event in project guardian by ichorpowered.

the class FlightCheck method getSequence.

@Override
public SequenceBlueprint<Event> getSequence(final Detection detection) {
    final Double analysisTime = detection.getContentContainer().get(ContentKeys.ANALYSIS_TIME).orElse(GuardianValue.empty()).getDirect().orElse(0d) / 0.05;
    final Double analysisIntercept = detection.getContentContainer().get(ContentKeys.ANALYSIS_INTERCEPT).orElse(GuardianValue.empty()).getDirect().orElse(0d);
    final Double minimumTickRate = detection.getContentContainer().get(ContentKeys.ANALYSIS_MINIMUM_TICK).orElse(GuardianValue.empty()).getDirect().orElse(0d) / 0.05;
    final Double maximumTickRate = detection.getContentContainer().get(ContentKeys.ANALYSIS_MAXIMUM_TICK).orElse(GuardianValue.empty()).getDirect().orElse(0d) / 0.05;
    return new GuardianSequenceBuilder().capture(new ControlCapture(detection.getPlugin(), detection)).capture(new AltitudeCapture(detection.getPlugin(), detection)).capture(new MaterialCapture(detection.getPlugin(), detection)).capture(new PotionEffectCapture(detection.getPlugin(), detection)).observe(MoveEntityEvent.class).after().delay(analysisTime.intValue()).condition(sequenceContext -> {
        final GuardianPlayerEntry<Player> entityEntry = sequenceContext.get(CommonContextKeys.ENTITY_ENTRY);
        final Summary summary = sequenceContext.get(CommonContextKeys.SUMMARY);
        final GuardianCaptureRegistry captureRegistry = sequenceContext.get(CommonContextKeys.CAPTURE_REGISTRY);
        final long lastActionTime = sequenceContext.get(CommonContextKeys.LAST_ACTION_TIME);
        summary.set(SequenceReport.class, new SequenceReport(false, Origin.source(sequenceContext.getRoot()).owner(entityEntry).build()));
        if (!entityEntry.getEntity(Player.class).isPresent())
            return false;
        final Player player = entityEntry.getEntity(Player.class).get();
        /*
                         * Capture Collection
                         */
        final CaptureContainer captureContainer = captureRegistry.getContainer();
        final Optional<Location> initial = captureContainer.get(GuardianSequence.INITIAL_LOCATION);
        final Optional<Double> effectLiftAmplifier = captureContainer.get(PotionEffectCapture.VERTICAL_SPEED_MODIFIER);
        final Optional<Double> materialSpeedAmplifier = captureContainer.get(MaterialCapture.SPEED_MODIFIER);
        final Optional<Double> altitude = captureContainer.get(AltitudeCapture.RELATIVE_ALTITUDE);
        final Optional<Map<String, Integer>> materialStateTicks = captureContainer.get(MaterialCapture.ACTIVE_MATERIAL_TICKS);
        final Optional<Map<String, Integer>> controlStateTicks = captureContainer.get(ControlCapture.ACTIVE_CONTROL_TICKS);
        if (!initial.isPresent() || !materialSpeedAmplifier.isPresent() || !altitude.isPresent() || !materialStateTicks.isPresent())
            return false;
        final Value<Double> playerBoxWidth = ContentUtil.getFirst(ContentKeys.BOX_PLAYER_WIDTH, entityEntry, detection.getContentContainer()).orElse(GuardianValue.empty());
        final Value<Double> playerBoxHeight = ContentUtil.getFirst(ContentKeys.BOX_PLAYER_HEIGHT, entityEntry, detection.getContentContainer()).orElse(GuardianValue.empty());
        final Value<Double> playerBoxSafety = ContentUtil.getFirst(ContentKeys.BOX_PLAYER_SAFETY, entityEntry, detection.getContentContainer()).orElse(GuardianValue.empty());
        final double playerWidth = playerBoxWidth.getDirect().orElse(1.2) + playerBoxSafety.getDirect().orElse(0.05);
        final double playerHeight = playerBoxHeight.getDirect().orElse(1.8) + playerBoxSafety.getDirect().orElse(0.05);
        final boolean isSneaking = player.get(Keys.IS_SNEAKING).isPresent() && player.get(Keys.IS_SNEAKING).get();
        final BoundingBox playerBox = WorldUtil.getBoundingBox(playerWidth, isSneaking ? (playerHeight - 0.15) : playerHeight);
        long current = System.currentTimeMillis();
        // Gets the average time between now and the last action.
        double averageActionTime = ((current - lastActionTime) / 1000) / 0.05;
        if (averageActionTime < minimumTickRate) {
            detection.getLogger().warn("The server may be overloaded. A check could not be completed.");
            return false;
        } else if (averageActionTime > maximumTickRate) {
            return false;
        }
        if (player.get(Keys.VEHICLE).isPresent() || (player.get(Keys.IS_FLYING).isPresent() && player.get(Keys.IS_FLYING).get()) || player.getLocation().getY() < 1)
            return false;
        final double intercept = analysisIntercept + (effectLiftAmplifier.orElse(0d) / analysisTime);
        // Gets the players vertical displacement in the world.
        final double verticalDisplacement = ((player.getLocation().getY() - initial.get().getY()) == 0) ? intercept : player.getLocation().getY() - initial.get().getY();
        // Gets the players relative altitude to the ground.
        final double averageAltitude = altitude.get() / averageActionTime;
        // Gets the time the player is on solid ground or a liquid.
        final int solidMaterialTime = materialStateTicks.get().get(MaterialCapture.SOLID);
        final int liquidMaterialTime = materialStateTicks.get().get(MaterialCapture.LIQUID);
        // Gets the time the player is using flight.
        final int flightControlTime = controlStateTicks.get().get(ControlCapture.FLY);
        if (verticalDisplacement <= 1 || averageAltitude <= 1 || WorldUtil.containsBlocksUnder(player.getLocation(), playerBox, 1d) || solidMaterialTime > 1 || liquidMaterialTime > 1 || flightControlTime > 1)
            return false;
        if (((verticalDisplacement / averageAltitude) + averageAltitude) > intercept) {
            // ------------------------- DEBUG -----------------------------
            System.out.println(player.getName() + " has been caught using fly hacks. (" + ((verticalDisplacement / averageAltitude) + averageAltitude) + ")");
            // -------------------------------------------------------------
            SequenceReport report = new SequenceReport(true, Origin.source(sequenceContext.getRoot()).owner(entityEntry).build());
            report.put("type", "Flight");
            report.put("information", Collections.singletonList("Gained altitude over " + ((verticalDisplacement / averageAltitude) + averageAltitude) + "."));
            report.put("initial_location", initial.get());
            report.put("final_location", player.getLocation());
            report.put("severity", ((verticalDisplacement / averageAltitude) + averageAltitude) / (verticalDisplacement + averageAltitude));
            summary.set(SequenceReport.class, report);
            return true;
        }
        return false;
    }, ConditionType.NORMAL).build(SequenceContext.builder().owner(detection).root(this).build());
}
Also used : GuardianSequenceBuilder(com.ichorpowered.guardian.sequence.GuardianSequenceBuilder) Summary(com.ichorpowered.guardianapi.detection.report.Summary) ContentKeys(com.ichorpowered.guardianapi.content.ContentKeys) Keys(org.spongepowered.api.data.key.Keys) GuardianValue(com.ichorpowered.guardian.util.item.mutable.GuardianValue) Origin(com.ichorpowered.guardianapi.event.origin.Origin) PotionEffectCapture(com.ichorpowered.guardian.common.capture.player.PotionEffectCapture) GuardianCaptureRegistry(com.ichorpowered.guardian.sequence.capture.GuardianCaptureRegistry) Value(com.ichorpowered.guardianapi.util.item.value.mutable.Value) SequenceReport(com.ichorpowered.guardian.sequence.SequenceReport) Map(java.util.Map) ConditionType(com.abilityapi.sequenceapi.action.condition.ConditionType) Location(org.spongepowered.api.world.Location) GuardianSequence(com.ichorpowered.guardian.sequence.GuardianSequence) ContentUtil(com.ichorpowered.guardian.util.ContentUtil) Event(org.spongepowered.api.event.Event) Set(java.util.Set) AltitudeCapture(com.ichorpowered.guardian.common.capture.player.AltitudeCapture) SequenceContext(com.abilityapi.sequenceapi.SequenceContext) Sets(com.google.common.collect.Sets) BoundingBox(com.ichorpowered.guardian.util.entity.BoundingBox) Check(com.ichorpowered.guardianapi.detection.check.Check) GuardianPlayerEntry(com.ichorpowered.guardian.entry.GuardianPlayerEntry) Detection(com.ichorpowered.guardianapi.detection.Detection) CommonContextKeys(com.ichorpowered.guardian.sequence.context.CommonContextKeys) CaptureContainer(com.ichorpowered.guardianapi.detection.capture.CaptureContainer) ControlCapture(com.ichorpowered.guardian.common.capture.player.ControlCapture) Optional(java.util.Optional) WorldUtil(com.ichorpowered.guardian.util.WorldUtil) Player(org.spongepowered.api.entity.living.player.Player) SequenceBlueprint(com.abilityapi.sequenceapi.SequenceBlueprint) MaterialCapture(com.ichorpowered.guardian.common.capture.world.MaterialCapture) Collections(java.util.Collections) MoveEntityEvent(org.spongepowered.api.event.entity.MoveEntityEvent) Player(org.spongepowered.api.entity.living.player.Player) Optional(java.util.Optional) AltitudeCapture(com.ichorpowered.guardian.common.capture.player.AltitudeCapture) ControlCapture(com.ichorpowered.guardian.common.capture.player.ControlCapture) SequenceReport(com.ichorpowered.guardian.sequence.SequenceReport) GuardianPlayerEntry(com.ichorpowered.guardian.entry.GuardianPlayerEntry) MaterialCapture(com.ichorpowered.guardian.common.capture.world.MaterialCapture) PotionEffectCapture(com.ichorpowered.guardian.common.capture.player.PotionEffectCapture) CaptureContainer(com.ichorpowered.guardianapi.detection.capture.CaptureContainer) BoundingBox(com.ichorpowered.guardian.util.entity.BoundingBox) GuardianValue(com.ichorpowered.guardian.util.item.mutable.GuardianValue) Value(com.ichorpowered.guardianapi.util.item.value.mutable.Value) Summary(com.ichorpowered.guardianapi.detection.report.Summary) GuardianSequenceBuilder(com.ichorpowered.guardian.sequence.GuardianSequenceBuilder) GuardianCaptureRegistry(com.ichorpowered.guardian.sequence.capture.GuardianCaptureRegistry)

Example 3 with Event

use of org.spongepowered.api.event.Event in project guardian by ichorpowered.

the class GuardianSequenceBuilder method build.

@Override
public final SequenceBlueprint<Event> build(final SequenceContext buildContext) {
    return new SequenceBlueprint<Event>() {

        @Override
        public final Sequence<Event> create(final Event rootEvent, final SequenceContext createContext) {
            final SequenceContext modifiedContext = SequenceContext.from(createContext).custom(CommonContextKeys.TRIGGER_CLASS, this.getTrigger()).custom(CommonContextKeys.TRIGGER_INSTANCE, rootEvent).merge(buildContext).build();
            final GuardianCaptureRegistry captureRegistry = new GuardianCaptureRegistry(modifiedContext.get(CommonContextKeys.ENTITY_ENTRY));
            GuardianSequenceBuilder.this.captures.forEach(capture -> captureRegistry.put(modifiedContext.getId(), capture.getClass(), capture));
            return new GuardianSequence(rootEvent, modifiedContext, this, captureRegistry, GuardianSequenceBuilder.this.actions);
        }

        @Override
        public final Class<? extends Event> getTrigger() {
            if (GuardianSequenceBuilder.this.actions.isEmpty())
                throw new NoSuchElementException("Sequence could not be established without an initial observer action.");
            if (GuardianSequenceBuilder.this.actions.get(0) instanceof ObserverAction) {
                return ((ObserverAction<Event>) GuardianSequenceBuilder.this.actions.get(0)).getEventClass();
            } else
                throw new ClassCastException("Sequence could not be established without an initial observer action.");
        }

        @Override
        public SequenceContext getContext() {
            return buildContext;
        }

        @Override
        public int hashCode() {
            return Objects.hash(buildContext.getOwner(), buildContext.getRoot(), getTrigger());
        }

        @Override
        public boolean equals(final Object other) {
            if (this == other)
                return true;
            if (other == null || !(other instanceof SequenceBlueprint<?>))
                return false;
            final SequenceBlueprint<?> that = (SequenceBlueprint<?>) other;
            return Objects.equals(buildContext.getOwner(), that.getContext().getOwner()) && Objects.equals(buildContext.getRoot(), that.getContext().getRoot()) && Objects.equals(getTrigger(), that.getTrigger());
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this).add("owner", buildContext.getOwner()).add("root", buildContext.getRoot()).add("trigger", getTrigger()).toString();
        }
    };
}
Also used : Event(org.spongepowered.api.event.Event) NoSuchElementException(java.util.NoSuchElementException) ObserverAction(com.abilityapi.sequenceapi.action.type.observe.ObserverAction) SequenceBlueprint(com.abilityapi.sequenceapi.SequenceBlueprint) SequenceContext(com.abilityapi.sequenceapi.SequenceContext) GuardianCaptureRegistry(com.ichorpowered.guardian.sequence.capture.GuardianCaptureRegistry)

Example 4 with Event

use of org.spongepowered.api.event.Event in project LanternServer by LanternPowered.

the class BanConfig method removeBan.

@Override
public boolean removeBan(Ban ban) {
    checkNotNull(ban, "ban");
    if (this.entries0.remove(ban)) {
        final CauseStack causeStack = CauseStack.currentOrEmpty();
        // Post the pardon events
        final Event event;
        final Cause cause = causeStack.getCurrentCause();
        if (ban instanceof Ban.Ip) {
            event = SpongeEventFactory.createPardonIpEvent(cause, (Ban.Ip) ban);
        } else {
            final Ban.Profile profileBan = (Ban.Profile) ban;
            // Check if the pardoned player is online (not yet been kicked)
            final Optional<Player> optTarget = Sponge.getServer().getPlayer(profileBan.getProfile().getUniqueId());
            if (optTarget.isPresent()) {
                event = SpongeEventFactory.createPardonUserEventTargetPlayer(cause, profileBan, optTarget.get(), optTarget.get());
            } else {
                event = SpongeEventFactory.createPardonUserEvent(cause, profileBan, Lantern.getGame().getServiceManager().provideUnchecked(UserStorageService.class).getOrCreate(profileBan.getProfile()));
            }
        }
        // Just ignore for now the fact that they may be cancellable,
        // only the PardonIpEvent seems to be cancellable
        // TODO: Should they all be cancellable or none of them?
        Sponge.getEventManager().post(event);
        return true;
    }
    return false;
}
Also used : UserStorageService(org.spongepowered.api.service.user.UserStorageService) CauseStack(org.lanternpowered.server.event.CauseStack) Player(org.spongepowered.api.entity.living.player.Player) Cause(org.spongepowered.api.event.cause.Cause) Ip(org.spongepowered.api.util.ban.Ban.Ip) Event(org.spongepowered.api.event.Event) Ban(org.spongepowered.api.util.ban.Ban) GameProfile(org.spongepowered.api.profile.GameProfile)

Example 5 with Event

use of org.spongepowered.api.event.Event in project LanternServer by LanternPowered.

the class FilterGenerator method generateClass.

byte[] generateClass(String name, Method method) {
    name = name.replace('.', '/');
    final Parameter[] params = method.getParameters();
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    MethodVisitor mv;
    cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, name, null, "java/lang/Object", new String[] { Type.getInternalName(EventFilter.class) });
    SubtypeFilterDelegate sfilter = null;
    final List<FilterDelegate> additional = new ArrayList<>();
    boolean cancellation = false;
    for (Annotation anno : method.getAnnotations()) {
        Object obj = filterFromAnnotation(anno.annotationType());
        if (obj == null) {
            continue;
        }
        if (obj instanceof SubtypeFilter) {
            if (sfilter != null) {
                throw new IllegalStateException("Cannot have both @Include and @Exclude annotations present at once");
            }
            sfilter = ((SubtypeFilter) obj).getDelegate(anno);
        } else if (obj instanceof EventTypeFilter) {
            final EventTypeFilter etf = (EventTypeFilter) obj;
            additional.add(etf.getDelegate(anno));
            if (etf == EventTypeFilter.CANCELLATION) {
                cancellation = true;
            }
        }
    }
    if (!cancellation && Cancellable.class.isAssignableFrom(method.getParameterTypes()[0])) {
        additional.add(new CancellationEventFilterDelegate(Tristate.FALSE));
    }
    if (sfilter != null) {
        sfilter.createFields(cw);
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        if (sfilter != null) {
            sfilter.writeCtor(name, cw, mv);
        }
        mv.visitInsn(RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "filter", "(" + Type.getDescriptor(Event.class) + ")[Ljava/lang/Object;", null, null);
        mv.visitCode();
        // index of the next available local variable
        int local = 2;
        if (sfilter != null) {
            local = sfilter.write(name, cw, mv, method, local);
        }
        for (FilterDelegate eventFilter : additional) {
            local = eventFilter.write(name, cw, mv, method, local);
        }
        // local var indices of the parameters values
        final int[] plocals = new int[params.length - 1];
        for (int i = 1; i < params.length; i++) {
            final Parameter param = params[i];
            ParameterFilterSourceDelegate source = null;
            final List<ParameterFilterDelegate> paramFilters = new ArrayList<>();
            for (Annotation anno : param.getAnnotations()) {
                Object obj = filterFromAnnotation(anno.annotationType());
                if (obj == null) {
                    continue;
                }
                if (obj instanceof ParameterSource) {
                    if (source != null) {
                        throw new IllegalStateException("Cannot have multiple parameter filter source annotations (for " + param.getName() + ")");
                    }
                    source = ((ParameterSource) obj).getDelegate(anno);
                } else if (obj instanceof ParameterFilter) {
                    paramFilters.add(((ParameterFilter) obj).getDelegate(anno));
                }
            }
            if (source == null) {
                throw new IllegalStateException("Cannot have additional parameters filters without a source (for " + param.getName() + ")");
            }
            if (source instanceof AllCauseFilterSourceDelegate && !paramFilters.isEmpty()) {
                // TODO until better handling for filtering arrays is added
                throw new IllegalStateException("Cannot have additional parameters filters without an array source (for " + param.getName() + ")");
            }
            final Tuple<Integer, Integer> localState = source.write(cw, mv, method, param, local);
            local = localState.getFirst();
            plocals[i - 1] = localState.getSecond();
            for (ParameterFilterDelegate paramFilter : paramFilters) {
                paramFilter.write(cw, mv, method, param, plocals[i - 1]);
            }
        }
        // create the return array
        if (params.length == 1) {
            mv.visitInsn(ICONST_1);
        } else {
            mv.visitIntInsn(BIPUSH, params.length);
        }
        mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
        // load the event into the array
        mv.visitInsn(DUP);
        mv.visitInsn(ICONST_0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitInsn(AASTORE);
        // load all the params into the array
        for (int i = 1; i < params.length; i++) {
            mv.visitInsn(DUP);
            mv.visitIntInsn(BIPUSH, i);
            Type paramType = Type.getType(params[i].getType());
            mv.visitVarInsn(paramType.getOpcode(ILOAD), plocals[i - 1]);
            GeneratorUtils.visitBoxingMethod(mv, paramType);
            mv.visitInsn(AASTORE);
        }
        mv.visitInsn(ARETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();
    final byte[] data = cw.toByteArray();
    if (FILTER_DEBUG) {
        final Path outDir = Paths.get(".sponge.debug.out");
        final Path outFile = outDir.resolve(name + ".class");
        if (!Files.exists(outFile.getParent())) {
            try {
                Files.createDirectories(outFile.getParent());
            } catch (IOException e) {
                Lantern.getLogger().warn("Unable to create the filter debug directory.", e);
            }
        }
        try (final OutputStream out = Files.newOutputStream(outFile)) {
            out.write(data);
        } catch (IOException e) {
            Lantern.getLogger().warn("Unable to create the filter debug class.", e);
        }
    }
    return data;
}
Also used : CancellationEventFilterDelegate(org.lanternpowered.server.event.filter.delegate.CancellationEventFilterDelegate) Cancellable(org.spongepowered.api.event.Cancellable) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ParameterFilterDelegate(org.lanternpowered.server.event.filter.delegate.ParameterFilterDelegate) MethodVisitor(org.objectweb.asm.MethodVisitor) List(java.util.List) ArrayList(java.util.ArrayList) Path(java.nio.file.Path) FilterDelegate(org.lanternpowered.server.event.filter.delegate.FilterDelegate) IncludeSubtypeFilterDelegate(org.lanternpowered.server.event.filter.delegate.IncludeSubtypeFilterDelegate) CancellationEventFilterDelegate(org.lanternpowered.server.event.filter.delegate.CancellationEventFilterDelegate) SubtypeFilterDelegate(org.lanternpowered.server.event.filter.delegate.SubtypeFilterDelegate) SupportsDataFilterDelegate(org.lanternpowered.server.event.filter.delegate.SupportsDataFilterDelegate) ParameterFilterDelegate(org.lanternpowered.server.event.filter.delegate.ParameterFilterDelegate) HasDataFilterDelegate(org.lanternpowered.server.event.filter.delegate.HasDataFilterDelegate) ExcludeSubtypeFilterDelegate(org.lanternpowered.server.event.filter.delegate.ExcludeSubtypeFilterDelegate) ParameterFilterSourceDelegate(org.lanternpowered.server.event.filter.delegate.ParameterFilterSourceDelegate) AllCauseFilterSourceDelegate(org.lanternpowered.server.event.filter.delegate.AllCauseFilterSourceDelegate) IOException(java.io.IOException) ClassWriter(org.objectweb.asm.ClassWriter) Annotation(java.lang.annotation.Annotation) IncludeSubtypeFilterDelegate(org.lanternpowered.server.event.filter.delegate.IncludeSubtypeFilterDelegate) SubtypeFilterDelegate(org.lanternpowered.server.event.filter.delegate.SubtypeFilterDelegate) ExcludeSubtypeFilterDelegate(org.lanternpowered.server.event.filter.delegate.ExcludeSubtypeFilterDelegate) Type(org.objectweb.asm.Type) Parameter(java.lang.reflect.Parameter) Event(org.spongepowered.api.event.Event) Tuple(org.spongepowered.api.util.Tuple)

Aggregations

Event (org.spongepowered.api.event.Event)13 Player (org.spongepowered.api.entity.living.player.Player)7 SequenceBlueprint (com.abilityapi.sequenceapi.SequenceBlueprint)5 SequenceContext (com.abilityapi.sequenceapi.SequenceContext)5 GuardianCaptureRegistry (com.ichorpowered.guardian.sequence.capture.GuardianCaptureRegistry)5 Origin (com.ichorpowered.guardianapi.event.origin.Origin)5 ConditionType (com.abilityapi.sequenceapi.action.condition.ConditionType)4 Sets (com.google.common.collect.Sets)4 GuardianPlayerEntry (com.ichorpowered.guardian.entry.GuardianPlayerEntry)4 GuardianSequence (com.ichorpowered.guardian.sequence.GuardianSequence)4 GuardianSequenceBuilder (com.ichorpowered.guardian.sequence.GuardianSequenceBuilder)4 SequenceReport (com.ichorpowered.guardian.sequence.SequenceReport)4 CommonContextKeys (com.ichorpowered.guardian.sequence.context.CommonContextKeys)4 Check (com.ichorpowered.guardianapi.detection.check.Check)4 ControlCapture (com.ichorpowered.guardian.common.capture.player.ControlCapture)3 PotionEffectCapture (com.ichorpowered.guardian.common.capture.player.PotionEffectCapture)3 GuardianValue (com.ichorpowered.guardian.util.item.mutable.GuardianValue)3 ContentKeys (com.ichorpowered.guardianapi.content.ContentKeys)3 Detection (com.ichorpowered.guardianapi.detection.Detection)3 CaptureContainer (com.ichorpowered.guardianapi.detection.capture.CaptureContainer)3