text:
// tag as surfaceflinger
#define LOG_TAG "SurfaceFlinger"

#include <stdint.h>
#include <sys/types.h>

#include <binder/Parcel.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>

#include <gui/IDisplayEventConnection.h>
#include <gui/IGraphicBufferProducer.h>
#include <gui/IRegionSamplingListener.h>
#include <gui/ISurfaceComposer.h>
#include <gui/ISurfaceComposerClient.h>
#include <gui/LayerDebugInfo.h>
#include <gui/LayerState.h>

#include <system/graphics.h>

#include <ui/DisplayInfo.h>
#include <ui/DisplayStatInfo.h>
#include <ui/HdrCapabilities.h>

#include <utils/Log.h>

/* M3E: add */
#define TF_ONE_WAY IBinder::FLAG_ONEWAY

// ---------------------------------------------------------------------------

namespace android {

using ui::ColorMode;

class BpSurfaceComposer : public BpInterface<ISurfaceComposer>
{
public:
    explicit BpSurfaceComposer(const sp<IBinder>& impl)
        : BpInterface<ISurfaceComposer>(impl)
    {
    }

    virtual ~BpSurfaceComposer();

    virtual sp<ISurfaceComposerClient> createConnection()
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        remote()->transact(BnSurfaceComposer::CREATE_CONNECTION, data, &reply);
        return interface_cast<ISurfaceComposerClient>(reply.readStrongBinder());
    }

    virtual void setTransactionState(const Vector<ComposerState>& state,
                                     const Vector<DisplayState>& displays, uint32_t flags,
                                     const sp<IBinder>& applyToken,
                                     const InputWindowCommands& commands,
                                     int64_t desiredPresentTime,
                                     const client_cache_t& uncacheBuffer,
                                     const std::vector<ListenerCallbacks>& listenerCallbacks) {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());

        data.writeUint32(static_cast<uint32_t>(state.size()));
        for (const auto& s : state) {
            s.write(data);
        }

        data.writeUint32(static_cast<uint32_t>(displays.size()));
        for (const auto& d : displays) {
            d.write(data);
        }

        data.writeUint32(flags);
        data.writeStrongBinder(applyToken);
        commands.write(data);
        data.writeInt64(desiredPresentTime);
        data.writeWeakBinder(uncacheBuffer.token);
        data.writeUint64(uncacheBuffer.id);

        if (data.writeVectorSize(listenerCallbacks) == NO_ERROR) {
            for (const auto& [listener, callbackIds] : listenerCallbacks) {
                data.writeStrongBinder(IInterface::asBinder(listener));
                data.writeInt64Vector(callbackIds);
            }
        }

        remote()->transact(BnSurfaceComposer::SET_TRANSACTION_STATE, data, &reply);
    }

    virtual void bootFinished()
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        remote()->transact(BnSurfaceComposer::BOOT_FINISHED, data, &reply);
    }

    virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
                                   bool& outCapturedSecureLayers, const ui::Dataspace reqDataspace,
                                   const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
                                   uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform,
                                   ISurfaceComposer::Rotation rotation, bool captureSecureLayers) {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        data.writeInt32(static_cast<int32_t>(reqDataspace));
        data.writeInt32(static_cast<int32_t>(reqPixelFormat));
        data.write(sourceCrop);
        data.writeUint32(reqWidth);
        data.writeUint32(reqHeight);
        data.writeInt32(static_cast<int32_t>(useIdentityTransform));
        data.writeInt32(static_cast<int32_t>(rotation));
        data.writeInt32(static_cast<int32_t>(captureSecureLayers));
        status_t result = remote()->transact(BnSurfaceComposer::CAPTURE_SCREEN, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("captureScreen failed to transact: %d", result);
            return result;
        }
        result = reply.readInt32();
        if (result != NO_ERROR) {
            ALOGE("captureScreen failed to readInt32: %d", result);
            return result;
        }

        *outBuffer = new GraphicBuffer();
        reply.read(**outBuffer);
        outCapturedSecureLayers = reply.readBool();

        return result;
    }

    virtual status_t captureScreen(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
                                   sp<GraphicBuffer>* outBuffer) {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeUint64(displayOrLayerStack);
        status_t result = remote()->transact(BnSurfaceComposer::CAPTURE_SCREEN_BY_ID, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("captureScreen failed to transact: %d", result);
            return result;
        }
        result = reply.readInt32();
        if (result != NO_ERROR) {
            ALOGE("captureScreen failed to readInt32: %d", result);
            return result;
        }

        *outDataspace = static_cast<ui::Dataspace>(reply.readInt32());
        *outBuffer = new GraphicBuffer();
        reply.read(**outBuffer);
        return result;
    }

    virtual status_t captureLayers(
            const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
            const ui::Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat,
            const Rect& sourceCrop,
            const std::unordered_set<sp<IBinder>, SpHash<IBinder>>& excludeLayers, float frameScale,
            bool childrenOnly) {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(layerHandleBinder);
        data.writeInt32(static_cast<int32_t>(reqDataspace));
        data.writeInt32(static_cast<int32_t>(reqPixelFormat));
        data.write(sourceCrop);
        data.writeInt32(excludeLayers.size());
        for (auto el : excludeLayers) {
            data.writeStrongBinder(el);
        }
        data.writeFloat(frameScale);
        data.writeBool(childrenOnly);
        status_t result = remote()->transact(BnSurfaceComposer::CAPTURE_LAYERS, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("captureLayers failed to transact: %d", result);
            return result;
        }
        result = reply.readInt32();
        if (result != NO_ERROR) {
            ALOGE("captureLayers failed to readInt32: %d", result);
            return result;
        }

        *outBuffer = new GraphicBuffer();
        reply.read(**outBuffer);

        return result;
    }

    virtual bool authenticateSurfaceTexture(
            const sp<IGraphicBufferProducer>& bufferProducer) const
    {
        Parcel data, reply;
        int err = NO_ERROR;
        err = data.writeInterfaceToken(
                ISurfaceComposer::getInterfaceDescriptor());
        if (err != NO_ERROR) {
            ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error writing "
                    "interface descriptor: %s (%d)", strerror(-err), -err);
            return false;
        }
        err = data.writeStrongBinder(IInterface::asBinder(bufferProducer));
        if (err != NO_ERROR) {
            ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error writing "
                    "strong binder to parcel: %s (%d)", strerror(-err), -err);
            return false;
        }
        err = remote()->transact(BnSurfaceComposer::AUTHENTICATE_SURFACE, data,
                &reply);
        if (err != NO_ERROR) {
            ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error "
                    "performing transaction: %s (%d)", strerror(-err), -err);
            return false;
        }
        int32_t result = 0;
        err = reply.readInt32(&result);
        if (err != NO_ERROR) {
            ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error "
                    "retrieving result: %s (%d)", strerror(-err), -err);
            return false;
        }
        return result != 0;
    }

    virtual status_t getSupportedFrameTimestamps(
            std::vector<FrameEvent>* outSupported) const {
        if (!outSupported) {
            return UNEXPECTED_NULL;
        }
        outSupported->clear();

        Parcel data, reply;

        status_t err = data.writeInterfaceToken(
                ISurfaceComposer::getInterfaceDescriptor());
        if (err != NO_ERROR) {
            return err;
        }

        err = remote()->transact(
                BnSurfaceComposer::GET_SUPPORTED_FRAME_TIMESTAMPS,
                data, &reply);
        if (err != NO_ERROR) {
            return err;
        }

        int32_t result = 0;
        err = reply.readInt32(&result);
        if (err != NO_ERROR) {
            return err;
        }
        if (result != NO_ERROR) {
            return result;
        }

        std::vector<int32_t> supported;
        err = reply.readInt32Vector(&supported);
        if (err != NO_ERROR) {
            return err;
        }

        outSupported->reserve(supported.size());
        for (int32_t s : supported) {
            outSupported->push_back(static_cast<FrameEvent>(s));
        }
        return NO_ERROR;
    }

    virtual sp<IDisplayEventConnection> createDisplayEventConnection(VsyncSource vsyncSource,
                                                                     ConfigChanged configChanged) {
        Parcel data, reply;
        sp<IDisplayEventConnection> result;
        int err = data.writeInterfaceToken(
                ISurfaceComposer::getInterfaceDescriptor());
        if (err != NO_ERROR) {
            return result;
        }
        data.writeInt32(static_cast<int32_t>(vsyncSource));
        data.writeInt32(static_cast<int32_t>(configChanged));
        err = remote()->transact(
                BnSurfaceComposer::CREATE_DISPLAY_EVENT_CONNECTION,
                data, &reply);
        if (err != NO_ERROR) {
            ALOGE("ISurfaceComposer::createDisplayEventConnection: error performing "
                    "transaction: %s (%d)", strerror(-err), -err);
            return result;
        }
        result = interface_cast<IDisplayEventConnection>(reply.readStrongBinder());
        return result;
    }

    virtual sp<IBinder> createDisplay(const String8& displayName, bool secure)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeString8(displayName);
        data.writeInt32(secure ? 1 : 0);
        remote()->transact(BnSurfaceComposer::CREATE_DISPLAY, data, &reply);
        return reply.readStrongBinder();
    }

    virtual void destroyDisplay(const sp<IBinder>& display)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        remote()->transact(BnSurfaceComposer::DESTROY_DISPLAY, data, &reply);
    }

    virtual std::vector<PhysicalDisplayId> getPhysicalDisplayIds() const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (remote()->transact(BnSurfaceComposer::GET_PHYSICAL_DISPLAY_IDS, data, &reply) ==
            NO_ERROR) {
            std::vector<PhysicalDisplayId> displayIds;
            if (reply.readUint64Vector(&displayIds) == NO_ERROR) {
                return displayIds;
            }
        }

        return {};
    }

    virtual sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeUint64(displayId);
        remote()->transact(BnSurfaceComposer::GET_PHYSICAL_DISPLAY_TOKEN, data, &reply);
        return reply.readStrongBinder();
    }

    virtual void setPowerMode(const sp<IBinder>& display, int mode)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        data.writeInt32(mode);
        remote()->transact(BnSurfaceComposer::SET_POWER_MODE, data, &reply);
    }

    virtual status_t getDisplayConfigs(const sp<IBinder>& display,
            Vector<DisplayInfo>* configs)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        remote()->transact(BnSurfaceComposer::GET_DISPLAY_CONFIGS, data, &reply);
        status_t result = reply.readInt32();
        if (result == NO_ERROR) {
            size_t numConfigs = reply.readUint32();
            configs->clear();
            configs->resize(numConfigs);
            for (size_t c = 0; c < numConfigs; ++c) {
                memcpy(&(configs->editItemAt(c)),
                        reply.readInplace(sizeof(DisplayInfo)),
                        sizeof(DisplayInfo));
            }
        }
        return result;
    }

    virtual status_t getDisplayStats(const sp<IBinder>& display,
            DisplayStatInfo* stats)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        remote()->transact(BnSurfaceComposer::GET_DISPLAY_STATS, data, &reply);
        status_t result = reply.readInt32();
        if (result == NO_ERROR) {
            memcpy(stats,
                    reply.readInplace(sizeof(DisplayStatInfo)),
                    sizeof(DisplayStatInfo));
        }
        return result;
    }

    virtual int getActiveConfig(const sp<IBinder>& display)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        remote()->transact(BnSurfaceComposer::GET_ACTIVE_CONFIG, data, &reply);
        return reply.readInt32();
    }

    virtual status_t setActiveConfig(const sp<IBinder>& display, int id)
    {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("setActiveConfig failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeStrongBinder(display);
        if (result != NO_ERROR) {
            ALOGE("setActiveConfig failed to writeStrongBinder: %d", result);
            return result;
        }
        result = data.writeInt32(id);
        if (result != NO_ERROR) {
            ALOGE("setActiveConfig failed to writeInt32: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::SET_ACTIVE_CONFIG, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("setActiveConfig failed to transact: %d", result);
            return result;
        }
        return reply.readInt32();
    }

    virtual status_t getDisplayColorModes(const sp<IBinder>& display,
            Vector<ColorMode>* outColorModes) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("getDisplayColorModes failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeStrongBinder(display);
        if (result != NO_ERROR) {
            ALOGE("getDisplayColorModes failed to writeStrongBinder: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::GET_DISPLAY_COLOR_MODES, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("getDisplayColorModes failed to transact: %d", result);
            return result;
        }
        result = static_cast<status_t>(reply.readInt32());
        if (result == NO_ERROR) {
            size_t numModes = reply.readUint32();
            outColorModes->clear();
            outColorModes->resize(numModes);
            for (size_t i = 0; i < numModes; ++i) {
                outColorModes->replaceAt(static_cast<ColorMode>(reply.readInt32()), i);
            }
        }
        return result;
    }

    virtual status_t getDisplayNativePrimaries(const sp<IBinder>& display,
            ui::DisplayPrimaries& primaries) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("getDisplayNativePrimaries failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeStrongBinder(display);
        if (result != NO_ERROR) {
            ALOGE("getDisplayNativePrimaries failed to writeStrongBinder: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::GET_DISPLAY_NATIVE_PRIMARIES, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("getDisplayNativePrimaries failed to transact: %d", result);
            return result;
        }
        result = reply.readInt32();
        if (result == NO_ERROR) {
            memcpy(&primaries, reply.readInplace(sizeof(ui::DisplayPrimaries)),
                    sizeof(ui::DisplayPrimaries));
        }
        return result;
    }

    virtual ColorMode getActiveColorMode(const sp<IBinder>& display) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("getActiveColorMode failed to writeInterfaceToken: %d", result);
            return static_cast<ColorMode>(result);
        }
        result = data.writeStrongBinder(display);
        if (result != NO_ERROR) {
            ALOGE("getActiveColorMode failed to writeStrongBinder: %d", result);
            return static_cast<ColorMode>(result);
        }
        result = remote()->transact(BnSurfaceComposer::GET_ACTIVE_COLOR_MODE, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("getActiveColorMode failed to transact: %d", result);
            return static_cast<ColorMode>(result);
        }
        return static_cast<ColorMode>(reply.readInt32());
    }

    virtual status_t setActiveColorMode(const sp<IBinder>& display,
            ColorMode colorMode) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("setActiveColorMode failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeStrongBinder(display);
        if (result != NO_ERROR) {
            ALOGE("setActiveColorMode failed to writeStrongBinder: %d", result);
            return result;
        }
        result = data.writeInt32(static_cast<int32_t>(colorMode));
        if (result != NO_ERROR) {
            ALOGE("setActiveColorMode failed to writeInt32: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::SET_ACTIVE_COLOR_MODE, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("setActiveColorMode failed to transact: %d", result);
            return result;
        }
        return static_cast<status_t>(reply.readInt32());
    }

    virtual status_t clearAnimationFrameStats() {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("clearAnimationFrameStats failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::CLEAR_ANIMATION_FRAME_STATS, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("clearAnimationFrameStats failed to transact: %d", result);
            return result;
        }
        return reply.readInt32();
    }

    virtual status_t getAnimationFrameStats(FrameStats* outStats) const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        remote()->transact(BnSurfaceComposer::GET_ANIMATION_FRAME_STATS, data, &reply);
        reply.read(*outStats);
        return reply.readInt32();
    }

    virtual status_t getHdrCapabilities(const sp<IBinder>& display,
            HdrCapabilities* outCapabilities) const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        status_t result = data.writeStrongBinder(display);
        if (result != NO_ERROR) {
            ALOGE("getHdrCapabilities failed to writeStrongBinder: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::GET_HDR_CAPABILITIES,
                data, &reply);
        if (result != NO_ERROR) {
            ALOGE("getHdrCapabilities failed to transact: %d", result);
            return result;
        }
        result = reply.readInt32();
        if (result == NO_ERROR) {
            result = reply.read(*outCapabilities);
        }
        return result;
    }

    virtual status_t enableVSyncInjections(bool enable) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("enableVSyncInjections failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeBool(enable);
        if (result != NO_ERROR) {
            ALOGE("enableVSyncInjections failed to writeBool: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::ENABLE_VSYNC_INJECTIONS, data, &reply,
                                    IBinder::FLAG_ONEWAY);
        if (result != NO_ERROR) {
            ALOGE("enableVSyncInjections failed to transact: %d", result);
            return result;
        }
        return result;
    }

    virtual status_t injectVSync(nsecs_t when) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("injectVSync failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeInt64(when);
        if (result != NO_ERROR) {
            ALOGE("injectVSync failed to writeInt64: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::INJECT_VSYNC, data, &reply,
                                    IBinder::FLAG_ONEWAY);
        if (result != NO_ERROR) {
            ALOGE("injectVSync failed to transact: %d", result);
            return result;
        }
        return result;
    }

    virtual status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
    {
        if (!outLayers) {
            return UNEXPECTED_NULL;
        }

        Parcel data, reply;

        status_t err = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (err != NO_ERROR) {
            return err;
        }

        err = remote()->transact(BnSurfaceComposer::GET_LAYER_DEBUG_INFO, data, &reply);
        if (err != NO_ERROR) {
            return err;
        }

        int32_t result = 0;
        err = reply.readInt32(&result);
        if (err != NO_ERROR) {
            return err;
        }
        if (result != NO_ERROR) {
            return result;
        }

        outLayers->clear();
        return reply.readParcelableVector(outLayers);
    }

    virtual status_t getCompositionPreference(ui::Dataspace* defaultDataspace,
                                              ui::PixelFormat* defaultPixelFormat,
                                              ui::Dataspace* wideColorGamutDataspace,
                                              ui::PixelFormat* wideColorGamutPixelFormat) const {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            return error;
        }
        error = remote()->transact(BnSurfaceComposer::GET_COMPOSITION_PREFERENCE, data, &reply);
        if (error != NO_ERROR) {
            return error;
        }
        error = static_cast<status_t>(reply.readInt32());
        if (error == NO_ERROR) {
            *defaultDataspace = static_cast<ui::Dataspace>(reply.readInt32());
            *defaultPixelFormat = static_cast<ui::PixelFormat>(reply.readInt32());
            *wideColorGamutDataspace = static_cast<ui::Dataspace>(reply.readInt32());
            *wideColorGamutPixelFormat = static_cast<ui::PixelFormat>(reply.readInt32());
        }
        return error;
    }

    virtual status_t getColorManagement(bool* outGetColorManagement) const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        remote()->transact(BnSurfaceComposer::GET_COLOR_MANAGEMENT, data, &reply);
        bool result;
        status_t err = reply.readBool(&result);
        if (err == NO_ERROR) {
            *outGetColorManagement = result;
        }
        return err;
    }

    virtual status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
                                                           ui::PixelFormat* outFormat,
                                                           ui::Dataspace* outDataspace,
                                                           uint8_t* outComponentMask) const {
        if (!outFormat || !outDataspace || !outComponentMask) return BAD_VALUE;
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);

        status_t error =
                remote()->transact(BnSurfaceComposer::GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES,
                                   data, &reply);
        if (error != NO_ERROR) {
            return error;
        }

        uint32_t value = 0;
        error = reply.readUint32(&value);
        if (error != NO_ERROR) {
            return error;
        }
        *outFormat = static_cast<ui::PixelFormat>(value);

        error = reply.readUint32(&value);
        if (error != NO_ERROR) {
            return error;
        }
        *outDataspace = static_cast<ui::Dataspace>(value);

        error = reply.readUint32(&value);
        if (error != NO_ERROR) {
            return error;
        }
        *outComponentMask = static_cast<uint8_t>(value);
        return error;
    }

    virtual status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
                                                      uint8_t componentMask,
                                                      uint64_t maxFrames) const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        data.writeBool(enable);
        data.writeByte(static_cast<int8_t>(componentMask));
        data.writeUint64(maxFrames);
        status_t result =
                remote()->transact(BnSurfaceComposer::SET_DISPLAY_CONTENT_SAMPLING_ENABLED, data,
                                   &reply);
        return result;
    }

    virtual status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
                                               uint64_t timestamp,
                                               DisplayedFrameStats* outStats) const {
        if (!outStats) return BAD_VALUE;

        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        data.writeStrongBinder(display);
        data.writeUint64(maxFrames);
        data.writeUint64(timestamp);

        status_t result =
                remote()->transact(BnSurfaceComposer::GET_DISPLAYED_CONTENT_SAMPLE, data, &reply);

        if (result != NO_ERROR) {
            return result;
        }

        result = reply.readUint64(&outStats->numFrames);
        if (result != NO_ERROR) {
            return result;
        }

        result = reply.readUint64Vector(&outStats->component_0_sample);
        if (result != NO_ERROR) {
            return result;
        }
        result = reply.readUint64Vector(&outStats->component_1_sample);
        if (result != NO_ERROR) {
            return result;
        }
        result = reply.readUint64Vector(&outStats->component_2_sample);
        if (result != NO_ERROR) {
            return result;
        }
        result = reply.readUint64Vector(&outStats->component_3_sample);
        return result;
    }

    virtual status_t getProtectedContentSupport(bool* outSupported) const {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        status_t error =
                remote()->transact(BnSurfaceComposer::GET_PROTECTED_CONTENT_SUPPORT, data, &reply);
        if (error != NO_ERROR) {
            return error;
        }
        error = reply.readBool(outSupported);
        return error;
    }

    virtual status_t isWideColorDisplay(const sp<IBinder>& token,
                                        bool* outIsWideColorDisplay) const {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            return error;
        }
        error = data.writeStrongBinder(token);
        if (error != NO_ERROR) {
            return error;
        }

        error = remote()->transact(BnSurfaceComposer::IS_WIDE_COLOR_DISPLAY, data, &reply);
        if (error != NO_ERROR) {
            return error;
        }
        error = reply.readBool(outIsWideColorDisplay);
        return error;
    }

    virtual status_t addRegionSamplingListener(const Rect& samplingArea,
                                               const sp<IBinder>& stopLayerHandle,
                                               const sp<IRegionSamplingListener>& listener) {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            ALOGE("addRegionSamplingListener: Failed to write interface token");
            return error;
        }
        error = data.write(samplingArea);
        if (error != NO_ERROR) {
            ALOGE("addRegionSamplingListener: Failed to write sampling area");
            return error;
        }
        error = data.writeStrongBinder(stopLayerHandle);
        if (error != NO_ERROR) {
            ALOGE("addRegionSamplingListener: Failed to write stop layer handle");
            return error;
        }
        error = data.writeStrongBinder(IInterface::asBinder(listener));
        if (error != NO_ERROR) {
            ALOGE("addRegionSamplingListener: Failed to write listener");
            return error;
        }
        error = remote()->transact(BnSurfaceComposer::ADD_REGION_SAMPLING_LISTENER, data, &reply);
        if (error != NO_ERROR) {
            ALOGE("addRegionSamplingListener: Failed to transact");
        }
        return error;
    }

    virtual status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            ALOGE("removeRegionSamplingListener: Failed to write interface token");
            return error;
        }
        error = data.writeStrongBinder(IInterface::asBinder(listener));
        if (error != NO_ERROR) {
            ALOGE("removeRegionSamplingListener: Failed to write listener");
            return error;
        }
        error = remote()->transact(BnSurfaceComposer::REMOVE_REGION_SAMPLING_LISTENER, data,
                                   &reply);
        if (error != NO_ERROR) {
            ALOGE("removeRegionSamplingListener: Failed to transact");
        }
        return error;
    }

    virtual status_t setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
                                              const std::vector<int32_t>& allowedConfigs) {
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("setAllowedDisplayConfigs failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeStrongBinder(displayToken);
        if (result != NO_ERROR) {
            ALOGE("setAllowedDisplayConfigs failed to writeStrongBinder: %d", result);
            return result;
        }
        result = data.writeInt32Vector(allowedConfigs);
        if (result != NO_ERROR) {
            ALOGE("setAllowedDisplayConfigs failed to writeInt32Vector: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::SET_ALLOWED_DISPLAY_CONFIGS, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("setAllowedDisplayConfigs failed to transact: %d", result);
            return result;
        }
        return reply.readInt32();
    }

    virtual status_t getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
                                              std::vector<int32_t>* outAllowedConfigs) {
        if (!outAllowedConfigs) return BAD_VALUE;
        Parcel data, reply;
        status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (result != NO_ERROR) {
            ALOGE("getAllowedDisplayConfigs failed to writeInterfaceToken: %d", result);
            return result;
        }
        result = data.writeStrongBinder(displayToken);
        if (result != NO_ERROR) {
            ALOGE("getAllowedDisplayConfigs failed to writeStrongBinder: %d", result);
            return result;
        }
        result = remote()->transact(BnSurfaceComposer::GET_ALLOWED_DISPLAY_CONFIGS, data, &reply);
        if (result != NO_ERROR) {
            ALOGE("getAllowedDisplayConfigs failed to transact: %d", result);
            return result;
        }
        result = reply.readInt32Vector(outAllowedConfigs);
        if (result != NO_ERROR) {
            ALOGE("getAllowedDisplayConfigs failed to readInt32Vector: %d", result);
            return result;
        }
        return reply.readInt32();
    }

    virtual status_t getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
                                                 bool* outSupport) const {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            ALOGE("getDisplayBrightnessSupport: failed to write interface token: %d", error);
            return error;
        }
        error = data.writeStrongBinder(displayToken);
        if (error != NO_ERROR) {
            ALOGE("getDisplayBrightnessSupport: failed to write display token: %d", error);
            return error;
        }
        error = remote()->transact(BnSurfaceComposer::GET_DISPLAY_BRIGHTNESS_SUPPORT, data, &reply);
        if (error != NO_ERROR) {
            ALOGE("getDisplayBrightnessSupport: failed to transact: %d", error);
            return error;
        }
        bool support;
        error = reply.readBool(&support);
        if (error != NO_ERROR) {
            ALOGE("getDisplayBrightnessSupport: failed to read support: %d", error);
            return error;
        }
        *outSupport = support;
        return NO_ERROR;
    }

    virtual status_t setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) const {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            ALOGE("setDisplayBrightness: failed to write interface token: %d", error);
            return error;
        }
        error = data.writeStrongBinder(displayToken);
        if (error != NO_ERROR) {
            ALOGE("setDisplayBrightness: failed to write display token: %d", error);
            return error;
        }
        error = data.writeFloat(brightness);
        if (error != NO_ERROR) {
            ALOGE("setDisplayBrightness: failed to write brightness: %d", error);
            return error;
        }
        error = remote()->transact(BnSurfaceComposer::SET_DISPLAY_BRIGHTNESS, data, &reply);
        if (error != NO_ERROR) {
            ALOGE("setDisplayBrightness: failed to transact: %d", error);
            return error;
        }
        return NO_ERROR;
    }

    virtual status_t notifyPowerHint(int32_t hintId) {
        Parcel data, reply;
        status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        if (error != NO_ERROR) {
            ALOGE("notifyPowerHint: failed to write interface token: %d", error);
            return error;
        }
        error = data.writeInt32(hintId);
        if (error != NO_ERROR) {
            ALOGE("notifyPowerHint: failed to write hintId: %d", error);
            return error;
        }
        error = remote()->transact(BnSurfaceComposer::NOTIFY_POWER_HINT, data, &reply,
                                   IBinder::FLAG_ONEWAY);
        if (error != NO_ERROR) {
            ALOGE("notifyPowerHint: failed to transact: %d", error);
            return error;
        }
        return NO_ERROR;
    }
};

// Out-of-line virtual method definition to trigger vtable emission in this
// translation unit (see clang warning -Wweak-vtables)
BpSurfaceComposer::~BpSurfaceComposer() {}

IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer");

// ----------------------------------------------------------------------

status_t BnSurfaceComposer::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    switch(code) {
        case CREATE_CONNECTION: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> b = IInterface::asBinder(createConnection());
            reply->writeStrongBinder(b);
            return NO_ERROR;
        }
        case SET_TRANSACTION_STATE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);

            size_t count = data.readUint32();
            if (count > data.dataSize()) {
                return BAD_VALUE;
            }
            Vector<ComposerState> state;
            state.setCapacity(count);
            for (size_t i = 0; i < count; i++) {
                ComposerState s;
                if (s.read(data) == BAD_VALUE) {
                    return BAD_VALUE;
                }
                state.add(s);
            }

            count = data.readUint32();
            if (count > data.dataSize()) {
                return BAD_VALUE;
            }
            DisplayState d;
            Vector<DisplayState> displays;
            displays.setCapacity(count);
            for (size_t i = 0; i < count; i++) {
                if (d.read(data) == BAD_VALUE) {
                    return BAD_VALUE;
                }
                displays.add(d);
            }

            uint32_t stateFlags = data.readUint32();
            sp<IBinder> applyToken = data.readStrongBinder();
            InputWindowCommands inputWindowCommands;
            inputWindowCommands.read(data);

            int64_t desiredPresentTime = data.readInt64();

            client_cache_t uncachedBuffer;
            uncachedBuffer.token = data.readWeakBinder();
            uncachedBuffer.id = data.readUint64();

            std::vector<ListenerCallbacks> listenerCallbacks;
            int32_t listenersSize = data.readInt32();
            for (int32_t i = 0; i < listenersSize; i++) {
                auto listener =
                        interface_cast<ITransactionCompletedListener>(data.readStrongBinder());
                std::vector<CallbackId> callbackIds;
                data.readInt64Vector(&callbackIds);
                listenerCallbacks.emplace_back(listener, callbackIds);
            }

            setTransactionState(state, displays, stateFlags, applyToken, inputWindowCommands,
                                desiredPresentTime, uncachedBuffer, listenerCallbacks);
            return NO_ERROR;
        }
        case BOOT_FINISHED: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            bootFinished();
            return NO_ERROR;
        }
        case CAPTURE_SCREEN: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = data.readStrongBinder();
            ui::Dataspace reqDataspace = static_cast<ui::Dataspace>(data.readInt32());
            ui::PixelFormat reqPixelFormat = static_cast<ui::PixelFormat>(data.readInt32());
            sp<GraphicBuffer> outBuffer;
            Rect sourceCrop(Rect::EMPTY_RECT);
            data.read(sourceCrop);
            uint32_t reqWidth = data.readUint32();
            uint32_t reqHeight = data.readUint32();
            bool useIdentityTransform = static_cast<bool>(data.readInt32());
            int32_t rotation = data.readInt32();
            bool captureSecureLayers = static_cast<bool>(data.readInt32());

            bool capturedSecureLayers = false;
            status_t res = captureScreen(display, &outBuffer, capturedSecureLayers, reqDataspace,
                                         reqPixelFormat, sourceCrop, reqWidth, reqHeight,
                                         useIdentityTransform,
                                         static_cast<ISurfaceComposer::Rotation>(rotation),
                                         captureSecureLayers);

            reply->writeInt32(res);
            if (res == NO_ERROR) {
                reply->write(*outBuffer);
                reply->writeBool(capturedSecureLayers);
            }
            return NO_ERROR;
        }
        case CAPTURE_SCREEN_BY_ID: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            uint64_t displayOrLayerStack = data.readUint64();
            ui::Dataspace outDataspace = ui::Dataspace::V0_SRGB;
            sp<GraphicBuffer> outBuffer;
            status_t res = captureScreen(displayOrLayerStack, &outDataspace, &outBuffer);
            reply->writeInt32(res);
            if (res == NO_ERROR) {
                reply->writeInt32(static_cast<int32_t>(outDataspace));
                reply->write(*outBuffer);
            }
            return NO_ERROR;
        }
        case CAPTURE_LAYERS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> layerHandleBinder = data.readStrongBinder();
            ui::Dataspace reqDataspace = static_cast<ui::Dataspace>(data.readInt32());
            ui::PixelFormat reqPixelFormat = static_cast<ui::PixelFormat>(data.readInt32());
            sp<GraphicBuffer> outBuffer;
            Rect sourceCrop(Rect::EMPTY_RECT);
            data.read(sourceCrop);

            std::unordered_set<sp<IBinder>, SpHash<IBinder>> excludeHandles;
            int numExcludeHandles = data.readInt32();
            excludeHandles.reserve(numExcludeHandles);
            for (int i = 0; i < numExcludeHandles; i++) {
                excludeHandles.emplace(data.readStrongBinder());
            }

            float frameScale = data.readFloat();
            bool childrenOnly = data.readBool();

            status_t res =
                    captureLayers(layerHandleBinder, &outBuffer, reqDataspace, reqPixelFormat,
                                  sourceCrop, excludeHandles, frameScale, childrenOnly);
            reply->writeInt32(res);
            if (res == NO_ERROR) {
                reply->write(*outBuffer);
            }
            return NO_ERROR;
        }
        case AUTHENTICATE_SURFACE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IGraphicBufferProducer> bufferProducer =
                    interface_cast<IGraphicBufferProducer>(data.readStrongBinder());
            int32_t result = authenticateSurfaceTexture(bufferProducer) ? 1 : 0;
            reply->writeInt32(result);
            return NO_ERROR;
        }
        case GET_SUPPORTED_FRAME_TIMESTAMPS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            std::vector<FrameEvent> supportedTimestamps;
            status_t result = getSupportedFrameTimestamps(&supportedTimestamps);
            status_t err = reply->writeInt32(result);
            if (err != NO_ERROR) {
                return err;
            }
            if (result != NO_ERROR) {
                return result;
            }

            std::vector<int32_t> supported;
            supported.reserve(supportedTimestamps.size());
            for (FrameEvent s : supportedTimestamps) {
                supported.push_back(static_cast<int32_t>(s));
            }
            return reply->writeInt32Vector(supported);
        }
        case CREATE_DISPLAY_EVENT_CONNECTION: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            auto vsyncSource = static_cast<ISurfaceComposer::VsyncSource>(data.readInt32());
            auto configChanged = static_cast<ISurfaceComposer::ConfigChanged>(data.readInt32());

            sp<IDisplayEventConnection> connection(
                    createDisplayEventConnection(vsyncSource, configChanged));
            reply->writeStrongBinder(IInterface::asBinder(connection));
            return NO_ERROR;
        }
        case CREATE_DISPLAY: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            String8 displayName = data.readString8();
            bool secure = bool(data.readInt32());
            sp<IBinder> display(createDisplay(displayName, secure));
            reply->writeStrongBinder(display);
            return NO_ERROR;
        }
        case DESTROY_DISPLAY: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = data.readStrongBinder();
            destroyDisplay(display);
            return NO_ERROR;
        }
        case GET_PHYSICAL_DISPLAY_TOKEN: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            PhysicalDisplayId displayId = data.readUint64();
            sp<IBinder> display = getPhysicalDisplayToken(displayId);
            reply->writeStrongBinder(display);
            return NO_ERROR;
        }
        case GET_DISPLAY_CONFIGS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            Vector<DisplayInfo> configs;
            sp<IBinder> display = data.readStrongBinder();
            status_t result = getDisplayConfigs(display, &configs);
            reply->writeInt32(result);
            if (result == NO_ERROR) {
                reply->writeUint32(static_cast<uint32_t>(configs.size()));
                for (size_t c = 0; c < configs.size(); ++c) {
                    memcpy(reply->writeInplace(sizeof(DisplayInfo)),
                            &configs[c], sizeof(DisplayInfo));
                }
            }
            return NO_ERROR;
        }
        case GET_DISPLAY_STATS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            DisplayStatInfo stats;
            sp<IBinder> display = data.readStrongBinder();
            status_t result = getDisplayStats(display, &stats);
            reply->writeInt32(result);
            if (result == NO_ERROR) {
                memcpy(reply->writeInplace(sizeof(DisplayStatInfo)),
                        &stats, sizeof(DisplayStatInfo));
            }
            return NO_ERROR;
        }
        case GET_ACTIVE_CONFIG: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = data.readStrongBinder();
            int id = getActiveConfig(display);
            reply->writeInt32(id);
            return NO_ERROR;
        }
        case SET_ACTIVE_CONFIG: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = data.readStrongBinder();
            int id = data.readInt32();
            status_t result = setActiveConfig(display, id);
            reply->writeInt32(result);
            return NO_ERROR;
        }
        case GET_DISPLAY_COLOR_MODES: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            Vector<ColorMode> colorModes;
            sp<IBinder> display = nullptr;
            status_t result = data.readStrongBinder(&display);
            if (result != NO_ERROR) {
                ALOGE("getDisplayColorModes failed to readStrongBinder: %d", result);
                return result;
            }
            result = getDisplayColorModes(display, &colorModes);
            reply->writeInt32(result);
            if (result == NO_ERROR) {
                reply->writeUint32(static_cast<uint32_t>(colorModes.size()));
                for (size_t i = 0; i < colorModes.size(); ++i) {
                    reply->writeInt32(static_cast<int32_t>(colorModes[i]));
                }
            }
            return NO_ERROR;
        }
        case GET_DISPLAY_NATIVE_PRIMARIES: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            ui::DisplayPrimaries primaries;
            sp<IBinder> display = nullptr;

            status_t result = data.readStrongBinder(&display);
            if (result != NO_ERROR) {
                ALOGE("getDisplayNativePrimaries failed to readStrongBinder: %d", result);
                return result;
            }

            result = getDisplayNativePrimaries(display, primaries);
            reply->writeInt32(result);
            if (result == NO_ERROR) {
                memcpy(reply->writeInplace(sizeof(ui::DisplayPrimaries)), &primaries,
                        sizeof(ui::DisplayPrimaries));
            }

            return NO_ERROR;
        }
        case GET_ACTIVE_COLOR_MODE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = nullptr;
            status_t result = data.readStrongBinder(&display);
            if (result != NO_ERROR) {
                ALOGE("getActiveColorMode failed to readStrongBinder: %d", result);
                return result;
            }
            ColorMode colorMode = getActiveColorMode(display);
            result = reply->writeInt32(static_cast<int32_t>(colorMode));
            return result;
        }
        case SET_ACTIVE_COLOR_MODE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = nullptr;
            status_t result = data.readStrongBinder(&display);
            if (result != NO_ERROR) {
                ALOGE("getActiveColorMode failed to readStrongBinder: %d", result);
                return result;
            }
            int32_t colorModeInt = 0;
            result = data.readInt32(&colorModeInt);
            if (result != NO_ERROR) {
                ALOGE("setActiveColorMode failed to readInt32: %d", result);
                return result;
            }
            result = setActiveColorMode(display,
                    static_cast<ColorMode>(colorModeInt));
            result = reply->writeInt32(result);
            return result;
        }
        case CLEAR_ANIMATION_FRAME_STATS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            status_t result = clearAnimationFrameStats();
            reply->writeInt32(result);
            return NO_ERROR;
        }
        case GET_ANIMATION_FRAME_STATS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            FrameStats stats;
            status_t result = getAnimationFrameStats(&stats);
            reply->write(stats);
            reply->writeInt32(result);
            return NO_ERROR;
        }
        case SET_POWER_MODE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = data.readStrongBinder();
            int32_t mode = data.readInt32();
            setPowerMode(display, mode);
            return NO_ERROR;
        }
        case GET_HDR_CAPABILITIES: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = nullptr;
            status_t result = data.readStrongBinder(&display);
            if (result != NO_ERROR) {
                ALOGE("getHdrCapabilities failed to readStrongBinder: %d",
                        result);
                return result;
            }
            HdrCapabilities capabilities;
            result = getHdrCapabilities(display, &capabilities);
            reply->writeInt32(result);
            if (result == NO_ERROR) {
                reply->write(capabilities);
            }
            return NO_ERROR;
        }
        case ENABLE_VSYNC_INJECTIONS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            bool enable = false;
            status_t result = data.readBool(&enable);
            if (result != NO_ERROR) {
                ALOGE("enableVSyncInjections failed to readBool: %d", result);
                return result;
            }
            return enableVSyncInjections(enable);
        }
        case INJECT_VSYNC: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            int64_t when = 0;
            status_t result = data.readInt64(&when);
            if (result != NO_ERROR) {
                ALOGE("enableVSyncInjections failed to readInt64: %d", result);
                return result;
            }
            return injectVSync(when);
        }
        case GET_LAYER_DEBUG_INFO: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            std::vector<LayerDebugInfo> outLayers;
            status_t result = getLayerDebugInfo(&outLayers);
            reply->writeInt32(result);
            if (result == NO_ERROR)
            {
                result = reply->writeParcelableVector(outLayers);
            }
            return result;
        }
        case GET_COMPOSITION_PREFERENCE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            ui::Dataspace defaultDataspace;
            ui::PixelFormat defaultPixelFormat;
            ui::Dataspace wideColorGamutDataspace;
            ui::PixelFormat wideColorGamutPixelFormat;
            status_t error =
                    getCompositionPreference(&defaultDataspace, &defaultPixelFormat,
                                             &wideColorGamutDataspace, &wideColorGamutPixelFormat);
            reply->writeInt32(error);
            if (error == NO_ERROR) {
                reply->writeInt32(static_cast<int32_t>(defaultDataspace));
                reply->writeInt32(static_cast<int32_t>(defaultPixelFormat));
                reply->writeInt32(static_cast<int32_t>(wideColorGamutDataspace));
                reply->writeInt32(static_cast<int32_t>(wideColorGamutPixelFormat));
            }
            return error;
        }
        case GET_COLOR_MANAGEMENT: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            bool result;
            status_t error = getColorManagement(&result);
            if (error == NO_ERROR) {
                reply->writeBool(result);
            }
            return error;
        }
        case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);

            sp<IBinder> display = data.readStrongBinder();
            ui::PixelFormat format;
            ui::Dataspace dataspace;
            uint8_t component = 0;
            auto result =
                    getDisplayedContentSamplingAttributes(display, &format, &dataspace, &component);
            if (result == NO_ERROR) {
                reply->writeUint32(static_cast<uint32_t>(format));
                reply->writeUint32(static_cast<uint32_t>(dataspace));
                reply->writeUint32(static_cast<uint32_t>(component));
            }
            return result;
        }
        case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);

            sp<IBinder> display = nullptr;
            bool enable = false;
            int8_t componentMask = 0;
            uint64_t maxFrames = 0;
            status_t result = data.readStrongBinder(&display);
            if (result != NO_ERROR) {
                ALOGE("setDisplayContentSamplingEnabled failure in reading Display token: %d",
                      result);
                return result;
            }

            result = data.readBool(&enable);
            if (result != NO_ERROR) {
                ALOGE("setDisplayContentSamplingEnabled failure in reading enable: %d", result);
                return result;
            }

            result = data.readByte(static_cast<int8_t*>(&componentMask));
            if (result != NO_ERROR) {
                ALOGE("setDisplayContentSamplingEnabled failure in reading component mask: %d",
                      result);
                return result;
            }

            result = data.readUint64(&maxFrames);
            if (result != NO_ERROR) {
                ALOGE("setDisplayContentSamplingEnabled failure in reading max frames: %d", result);
                return result;
            }

            return setDisplayContentSamplingEnabled(display, enable,
                                                    static_cast<uint8_t>(componentMask), maxFrames);
        }
        case GET_DISPLAYED_CONTENT_SAMPLE: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);

            sp<IBinder> display = data.readStrongBinder();
            uint64_t maxFrames = 0;
            uint64_t timestamp = 0;

            status_t result = data.readUint64(&maxFrames);
            if (result != NO_ERROR) {
                ALOGE("getDisplayedContentSample failure in reading max frames: %d", result);
                return result;
            }

            result = data.readUint64(&timestamp);
            if (result != NO_ERROR) {
                ALOGE("getDisplayedContentSample failure in reading timestamp: %d", result);
                return result;
            }

            DisplayedFrameStats stats;
            result = getDisplayedContentSample(display, maxFrames, timestamp, &stats);
            if (result == NO_ERROR) {
                reply->writeUint64(stats.numFrames);
                reply->writeUint64Vector(stats.component_0_sample);
                reply->writeUint64Vector(stats.component_1_sample);
                reply->writeUint64Vector(stats.component_2_sample);
                reply->writeUint64Vector(stats.component_3_sample);
            }
            return result;
        }
        case GET_PROTECTED_CONTENT_SUPPORT: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            bool result;
            status_t error = getProtectedContentSupport(&result);
            if (error == NO_ERROR) {
                reply->writeBool(result);
            }
            return error;
        }
        case IS_WIDE_COLOR_DISPLAY: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> display = nullptr;
            status_t error = data.readStrongBinder(&display);
            if (error != NO_ERROR) {
                return error;
            }
            bool result;
            error = isWideColorDisplay(display, &result);
            if (error == NO_ERROR) {
                reply->writeBool(result);
            }
            return error;
        }
        case GET_PHYSICAL_DISPLAY_IDS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            return reply->writeUint64Vector(getPhysicalDisplayIds());
        }
        case ADD_REGION_SAMPLING_LISTENER: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            Rect samplingArea;
            status_t result = data.read(samplingArea);
            if (result != NO_ERROR) {
                ALOGE("addRegionSamplingListener: Failed to read sampling area");
                return result;
            }
            sp<IBinder> stopLayerHandle;
            result = data.readNullableStrongBinder(&stopLayerHandle);
            if (result != NO_ERROR) {
                ALOGE("addRegionSamplingListener: Failed to read stop layer handle");
                return result;
            }
            sp<IRegionSamplingListener> listener;
            result = data.readNullableStrongBinder(&listener);
            if (result != NO_ERROR) {
                ALOGE("addRegionSamplingListener: Failed to read listener");
                return result;
            }
            return addRegionSamplingListener(samplingArea, stopLayerHandle, listener);
        }
        case REMOVE_REGION_SAMPLING_LISTENER: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IRegionSamplingListener> listener;
            status_t result = data.readNullableStrongBinder(&listener);
            if (result != NO_ERROR) {
                ALOGE("removeRegionSamplingListener: Failed to read listener");
                return result;
            }
            return removeRegionSamplingListener(listener);
        }
        case SET_ALLOWED_DISPLAY_CONFIGS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> displayToken = data.readStrongBinder();
            std::vector<int32_t> allowedConfigs;
            data.readInt32Vector(&allowedConfigs);
            status_t result = setAllowedDisplayConfigs(displayToken, allowedConfigs);
            reply->writeInt32(result);
            return result;
        }
        case GET_ALLOWED_DISPLAY_CONFIGS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> displayToken = data.readStrongBinder();
            std::vector<int32_t> allowedConfigs;
            status_t result = getAllowedDisplayConfigs(displayToken, &allowedConfigs);
            reply->writeInt32Vector(allowedConfigs);
            reply->writeInt32(result);
            return result;
        }
        case GET_DISPLAY_BRIGHTNESS_SUPPORT: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> displayToken;
            status_t error = data.readNullableStrongBinder(&displayToken);
            if (error != NO_ERROR) {
                ALOGE("getDisplayBrightnessSupport: failed to read display token: %d", error);
                return error;
            }
            bool support = false;
            error = getDisplayBrightnessSupport(displayToken, &support);
            reply->writeBool(support);
            return error;
        }
        case SET_DISPLAY_BRIGHTNESS: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> displayToken;
            status_t error = data.readNullableStrongBinder(&displayToken);
            if (error != NO_ERROR) {
                ALOGE("setDisplayBrightness: failed to read display token: %d", error);
                return error;
            }
            float brightness = -1.0f;
            error = data.readFloat(&brightness);
            if (error != NO_ERROR) {
                ALOGE("setDisplayBrightness: failed to read brightness: %d", error);
                return error;
            }
            return setDisplayBrightness(displayToken, brightness);
        }
        case NOTIFY_POWER_HINT: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            int32_t hintId;
            status_t error = data.readInt32(&hintId);
            if (error != NO_ERROR) {
                ALOGE("notifyPowerHint: failed to read hintId: %d", error);
                return error;
            }
            return notifyPowerHint(hintId);
        }
        default: {
            return BBinder::onTransact(code, data, reply, flags);
        }
    }
}

} // namespace android


text:
This sample demonstrates how one can develop a home app for Windows 10 IoT Core.
The sample consist of two sets of app showing two different approaches:

## IoTHomeApp

Demonstrates how one can use LaunchUriAsync to launch other apps registered for a 'protocol'.
The solution folder contains OemApp1 and OemApp2 projects that supports protocol 'oemapp1' and 'oemapp2'.
The app also shows how to resolve ambiguity, in case of multiple apps registered for a protocol, by providing the App Id of the target application in the Launcher options.

OemApp1 amd OemApp2 must be built and deployed before one can use IotHomeApp to launch them.

## IoTStartApp

IotStartApp illustrates how one can use PackageManager APIs to enumerate and launch apps installed on the system, just like a Start screen.
In order to use the PackageManager APIs, it uses a restricted capability. This may make it difficult to pass the Store certification process.

However, one can always sideload the app onto the device.

redpajama_set_name: RedPajamaGithub


text:
@import '../variables.css';

.redtext {
  color: red;
}


text:
import os
import signal

import fooster.web
import fooster.web.query

import mcp.error

import mcp.common.http

import mcp.model.source

class Index(mcp.common.http.AuthHandler):
    group = 0

    def do_get(self):
        if not self.auth.admin:
            raise fooster.web.HTTPError(403)

        return 200, [dict(source) for source in mcp.model.source.items()]

    def do_post(self):
        if not self.auth.admin:
            raise fooster.web.HTTPError(403)

        try:
            mcp.model.source.add(self.request.body['source'], self.request.body['url'])
        except (KeyError, TypeError):
            raise fooster.web.HTTPError(400)
        except mcp.error.BzrError:
            raise fooster.web.HTTPError(400)
        except mcp.error.InvalidSourceError:
            raise fooster.web.HTTPError(403)
        except mcp.error.SourceExistsError:
            raise fooster.web.HTTPError(409)

        self.response.headers['Location'] = '/api/source/' + self.request.body['source']

        return 201, dict(mcp.model.source.get(self.request.body['source']))

class Source(mcp.common.http.AuthHandler):
    group = 1

    def do_get(self):
        if not self.auth.admin:
            raise fooster.web.HTTPError(404)

        try:
            return 200, dict(mcp.model.source.get(self.groups[0]))
        except mcp.error.NoSourceError:
            raise fooster.web.HTTPError(404)

    def do_put(self):
        if not self.auth.admin:
            raise fooster.web.HTTPError(404)

        try:
            mcp.model.source.update(self.groups[0])
        except mcp.error.NoSourceError:
            raise fooster.web.HTTPError(404)

        return 200, dict(mcp.model.source.get(self.groups[0]))

    def do_delete(self):
        if not self.auth.admin:
            raise fooster.web.HTTPError(404)

        try:
            mcp.model.source.remove(self.groups[0])
        except mcp.error.NoSourceError:
            raise fooster.web.HTTPError(404)

        return 204, None

routes = {'/api/source/' + fooster.web.query.regex: Index, '/api/source/(' + mcp.model.source.sources_allowed + ')' + fooster.web.query.regex: Source}


text:
========
Settings
========

How to customize the settings to suit your needs.

ADMIN_URL_BASE (Default: r"^admin/")
====================================

Used to control the URL for the admin in production.

FRAMEWORK_TITLE (Default: "Django")
====================================

Used to create the name of the site.

PACKAGINATOR_SEARCH_PREFIX (Default: "django")
==============================================

Autocomplete searches for something like 'forms' was problematic because so many packages start with 'django'. This prefix is accommodated in searches to prevent this sort of problem.

example::

    PACKAGINATOR_SEARCH_PREFIX = 'django'

PACKAGINATOR_HELP_TEXT (Default: Included in settings.py)
=========================================================

Used in the Package add/edit form in both the admin and the UI, these are assigned to model form help text arguments. Takes a dict of the following items:

Example (also the default)::

    PACKAGINATOR_HELP_TEXT = {
        "REPO_URL" : "Enter your project repo hosting URL here.
Example: https://bitbucket.org/ubernostrum/django-registration",
        "PYPI_URL" : "Leave this blank if this package does not have a PyPI release.
What PyPI uses to index your package.
Example: django-registration"
    }

Permissions Settings
====================

Django Packages provides several ways to control who can make what changes to
things like packages, features, and grids. By default, a Django Packages project
is open to contributions from any registered user. If a given project would
like more control over this, there are two settings that can be used.

    RESTRICT_PACKAGE_EDITORS
    RESTRICT_GRID_EDITORS

If these are not set, the assumption is that you do not want to restrict
editing.

If set to True, a user must have permission to add or edit the given object.
These permissions are set in the Django admin, and can be applied per user, or per group.

Settings that are on by default
-------------------------------

By default registered users can do the following:

**Packages**

* Can add package
* Can change package

**Grids**

* Can add Package
* Can change Package
* Can add feature
* Can change feature
* Can change element

In the default condition, only super users or those with permission can delete.

Testing permissions in templates
--------------------------------

A context processor will add the user profile to every template context, the
profile model also handles checking for permissions::

    {% if profile.can_edit_package %}
        <edit package UI here>
    {% endif %}

The follow properties can be used in templates:

* can_add_package
* can_edit_package
* can_edit_grid
* can_add_grid
* can_add_grid_feature
* can_edit_grid_feature
* can_delete_grid_feature
* can_add_grid_package
* can_delete_grid_package
* can_edit_grid_element

.. _troubleshooting: troubleshooting.html


text:
package ucar.ui.widget;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Wrap an action listener to filter on event type.
 * Prevent the delegate from causing more events.
 */
public class ActionListenerAdapter implements ActionListener {
  private final String actionCommand;
  private final ActionListener delegate;

  /**
   * Recieve events only when event type equals actionCommand name.
   */
  public ActionListenerAdapter(String actionCommand, ActionListener delegate) {
    this.actionCommand = actionCommand;
    this.delegate = delegate;
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals(actionCommand)) {
      delegate.actionPerformed(e);
    }
  }
}


text:
package org.keycloak.common.util;

import java.util.Date;

/**
 * @author Stian Thorgersen
 */
public class Time {

    private static int offset;

    /**
     * Returns current time in seconds adjusted by adding {@link #offset) seconds.
     * @return see description
     */
    public static int currentTime() {
        return ((int) (System.currentTimeMillis() / 1000)) + offset;
    }

    /**
     * Returns current time in milliseconds adjusted by adding {@link #offset) seconds.
     * @return see description
     */
    public static long currentTimeMillis() {
        return System.currentTimeMillis() + (offset * 1000);
    }

    /**
     * Returns {@link Date} object, its value set to time
     * @param time Time in milliseconds since the epoch
     * @return see description
     */
    public static Date toDate(int time) {
        return new Date(((long) time ) * 1000);
    }

    /**
     * Returns time in milliseconds for a time in seconds. No adjustment is made to the parameter.
     * @param time Time in seconds since the epoch
     * @return Time in milliseconds
     */
    public static long toMillis(int time) {
        return ((long) time) * 1000;
    }

    /**
     * @return Time offset in seconds that will be added to {@link #currentTime()} and {@link #currentTimeMillis()}.
     */
    public static int getOffset() {
        return offset;
    }

    /**
     * Sets time offset in seconds that will be added to {@link #currentTime()} and {@link #currentTimeMillis()}.
     * @param offset Offset (in seconds)
     */
    public static void setOffset(int offset) {
        Time.offset = offset;
    }

}


text:
layout:     post
title:      CAS Vulnerability Disclosure
summary:    Disclosure of issue with the Apache Commons Collections
tags:       [CAS]
---

# Remember

This post is **NOT** new. I am just collecting it here so it's publicly available.
This was originally published as a secret gist on Github in April 2016.

# Overview

This is an Apereo CAS project vulnerability disclosure, describing an issue in CAS's attempts to deserialize objects via the Apache Commons Collections library.

# Affected Deployments

The attack vector specifically applies to all deployments of CAS `v4.1.x` and `v4.2.x` deployments where the out-of-the-box default configuration of CAS is used for managing object serialization, encryption and signing of data.

You are **NOT** affected by this issue, if:

- You have deployed a different CAS version, lower than `v4.1.0`.
- You have deployed CAS `v4.1.x` or `v4.2.x`, **BUT** you have removed the default CAS configuration for encryption/signing and have regenerated the appropriate settings for your own deployment.

Exploiting the vulnerability hinges on getting the JVM to de-serialize Java objects from arbitrary serialized data. If the above conditions describe your deployment, we **STRONGLY** recommend that you take necessary action to patch your deployment based on the below instructions.

# Severity

This is a very serious issue where successfully exercising this vulnerability allows the adversary to inject arbitrary code. This disclosure is about a specific exploit path involving a bugged version of Apache Commons Collections. This exploit path is only an instance of a larger JVM Java object deserialization security concern.

# Patching

Patch releases are now available to address CAS `v4.1.x` and `v4.2.x` deployments. Upgrades to the next patch version for each release should be a drop-in replacement, with some effort to appropriately reconfigure CAS encryption/signing settings via the `cas.properties` file.

## CAS 4.1.x

### Overlay
Modify your CAS overlay to point to version `4.1.7`.

A snippet of a `pom.xml` for a CAS overlay follows:

```xml
...

<dependencies>
    <dependency>
        <groupId>org.jasig.cas</groupId>
        <artifactId>cas-server-webapp</artifactId>
        <version>${cas.version}</version>
        <type>war</type>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<properties>
    <cas.version>4.1.7</cas.version>
</properties>
...
```

### TGC Settings

Locate your `cas.properties` file and find the `tgc.*` settings.

- If your CAS deployment is **NOT** using the default encryption/signing keys provided by CAS and you have regenerated new keys and have replaced the default, you can safely ignore this step and leave your key configuration of signing/encryption in place without any further changes.

- If your CAS deployment **IS** using the default encryption/signing keys provided by CAS and you have **NOT** regenerated new keys to replace the default, you **MUST** take action to regenerate the keys.

You can choose one of the two approaches described below to handle key regeneration.

#### 1) Let CAS Generate Keys

Blank/comment out the following `tgc` settings:

```properties
# tgc.encryption.key=
# tgc.signing.key=
```

Build and deploy your CAS deployment once. Upon startup, CAS will notice that no keys are defined, and it will appropriately generate keys for you automatically. Your CAS logs will then show the following snippet:

```bash
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Secret key for encryption is not defined. CAS will attempt to auto-generate the encryption key>
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Generated encryption key ABC of size ... . The generated key MUST be added to CAS settings.>
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Secret key for signing is not defined. CAS will attempt to auto-generate the signing key>
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Generated signing key XYZ of size ... . The generated key MUST be added to CAS settings.>
```

You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
tgc.encryption.key=ABC
tgc.signing.key=XYZ
```

#### 2) Manually Generate Keys

Using a `git` client, clone and build the following project:

```bash
git clone https://github.com/mitreid-connect/json-web-key-generator.git
cd json-web-key-generator
mvn clean package
cd target

# Encryption Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 256

#
# Full key:
# {
#   "kty": "oct",
#   "k": "ABC"
# }
#

# Signing Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 512

# Full key:
# {
#   "kty": "oct",
#   "k": "XYZ"
# }

```
You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
tgc.encryption.key=ABC
tgc.signing.key=XYZ
```

### Webflow Settings

Locate your `cas.properties` file and find the `webflow.*` settings. If you do not see them in your configuration, go ahead and define them:

```properties
# webflow.encryption.key=
# webflow.signing.key=
```

You can choose one of the two approaches described below to handle key regeneration.

#### 1) Let CAS Generate Keys

Blank/comment out the following `webflow` settings:

```properties
# webflow.encryption.key=
# webflow.signing.key=
```

Build and deploy your CAS deployment once. Upon startup, CAS will notice that no keys are defined, and it will appropriately generate keys for you automatically. Your CAS logs will then show the following snippet:

```bash
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Secret key for encryption is not defined. CAS will attempt to auto-generate the encryption key>
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Generated encryption key ABC of size ... . The generated key MUST be added to CAS settings.>
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Secret key for signing is not defined. CAS will attempt to auto-generate the signing key>
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Generated signing key XYZ of size ... . The generated key MUST be added to CAS settings.>
```

You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
webflow.encryption.key=ABC
webflow.signing.key=XYZ
```

#### 2) Manually Generate Keys

Using a `git` client, clone and build the following project:

```bash
git clone https://github.com/mitreid-connect/json-web-key-generator.git
cd json-web-key-generator
mvn clean package
cd target

# Encryption Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 96

#
# Full key:
# {
#   "kty": "oct",
#   "k": "ABC"
# }
#

# Signing Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 512

# Full key:
# {
#   "kty": "oct",
#   "k": "XYZ"
# }

```
You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
webflow.encryption.key=ABC
webflow.signing.key=XYZ
```

### XML Configuration

If you have manually overridden the `cas-servlet.xml` file, you will need to make sure the following blocks are present
in the configuration:

```xml

Note that the Person Directory project requires the following configuration in CAS overlays:

```xml

Note that the Person Directory project requires the following configuration in CAS overlays:

```xml
<bean id="loginFlowStateTranscoder" class="org.jasig.spring.webflow.plugin.EncryptedTranscoder"
        c:cipherBean-ref="loginFlowCipherBean" />

<bean id="loginFlowCipherBean" class="org.jasig.cas.web.flow.CasWebflowCipherBean"
    c:cipherExecutor-ref="webflowCipherExecutor" />

<bean id="webflowCipherExecutor" class="org.jasig.cas.util.BinaryCipherExecutor"
    c:encryptionSecretKey="${webflow.encryption.key:}"
    c:signingSecretKey="${webflow.signing.key:}"/>
```

Re-adjust the beans accordingly, and remove the built-in keystore.

### Finally
Rebuild and redeploy your CAS overlay.

## CAS 4.2.x

Modify your CAS overlay to point to version `4.2.1`.

A snippet of a `pom.xml` for a CAS overlay follows:

```xml
...

<dependencies>
    <dependency>
        <groupId>org.jasig.cas</groupId>
        <artifactId>cas-server-webapp</artifactId>
        <version>${cas.version}</version>
        <type>war</type>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<properties>
    <cas.version>4.2.1</cas.version>
</properties>
...
```

### TGC Settings

Locate your `cas.properties` file and find the `tgc.*` settings.

- If your CAS deployment is **NOT** using the default encryption/signing keys provided by CAS and you have regenerated new keys and have replaced the default, you can safely ignore this step and leave your key configuration of signing/encryption in place without any further changes.

- If your CAS deployment **IS** using the default encryption/signing keys provided by CAS and you have **NOT** regenerated new keys to replace the default, you **MUST** take action to regenerate the keys.

You can choose one of the two approaches described below to handle key regeneration.

#### 1) Let CAS Generate Keys

Blank/comment out the following `tgc` settings:

```properties
# tgc.encryption.key=
# tgc.signing.key=
```

Build and deploy your CAS deployment. Upon startup, CAS will notice that no keys are defined, and it will appropriately generate keys for you automatically. Your CAS logs will then show the following snippet:

```bash
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Secret key for encryption is not defined. CAS will attempt to auto-generate the encryption key>
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Generated encryption key ABC of size ... . The generated key MUST be added to CAS settings.>
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Secret key for signing is not defined. CAS will attempt to auto-generate the signing key>
WARN [org.jasig.cas.util.BaseStringCipherExecutor] - <Generated signing key XYZ of size ... . The generated key MUST be added to CAS settings.>
```

You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
tgc.encryption.key=ABC
tgc.signing.key=XYZ
```
Rebuild and redeploy your CAS overlay.

#### 2) Manually Generate Keys

Using a `git` client, clone and build the following project:

```bash
git clone https://github.com/mitreid-connect/json-web-key-generator.git
cd json-web-key-generator
mvn clean package
cd target

# Encryption Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 256

#
# Full key:
# {
#   "kty": "oct",
#   "k": "ABC"
# }
#

# Signing Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 512

# Full key:
# {
#   "kty": "oct",
#   "k": "XYZ"
# }

```
You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
tgc.encryption.key=ABC
tgc.signing.key=XYZ
```

### Webflow Settings

Locate your `cas.properties` file and find the `webflow.*` settings. If you do not see them in your configuration, go ahead and define them:

```properties
# webflow.encryption.key=
# webflow.signing.key=
```

You can choose one of the two approaches described below to handle key regeneration.

#### 1) Let CAS Generate Keys

Blank/comment out the following `webflow` settings:

```properties
# webflow.encryption.key=
# webflow.signing.key=
```

Build and deploy your CAS deployment once. Upon startup, CAS will notice that no keys are defined, and it will appropriately generate keys for you automatically. Your CAS logs will then show the following snippet:

```bash
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Secret key for encryption is not defined. CAS will attempt to auto-generate the encryption key>
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Generated encryption key ABC of size ... . The generated key MUST be added to CAS settings.>
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Secret key for signing is not defined. CAS will attempt to auto-generate the signing key>
WARN [org.jasig.cas.util.BinaryCipherExecutor] - <Generated signing key XYZ of size ... . The generated key MUST be added to CAS settings.>
```

You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
webflow.encryption.key=ABC
webflow.signing.key=XYZ
```

#### 2) Manually Generate Keys

Using a `git` client, clone and build the following project:

```bash
git clone https://github.com/mitreid-connect/json-web-key-generator.git
cd json-web-key-generator
mvn clean package
cd target

# Encryption Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 96

#
# Full key:
# {
#   "kty": "oct",
#   "k": "ABC"
# }
#

# Signing Key
java -jar json-web-key-generator-0.3-SNAPSHOT-jar-with-dependencies.jar -t oct -s 512

# Full key:
# {
#   "kty": "oct",
#   "k": "XYZ"
# }

```
You should then grab each generated key for encryption and signing, and put them inside your `cas.properties` file for each now-enabled setting:

```properties
webflow.encryption.key=ABC
webflow.signing.key=XYZ
```

### Finally
Rebuild and redeploy your CAS overlay.

# Clustered CAS Deployments

If you are running a cluster of CAS nodes, please be advised that the newly generated keys for all settings (regardless of the method of generation, whether CAS or you) **MUST** be shared with all CAS nodes in form of either a centralized or replicated/shared `cas.properties` file.

Failure to do so will completely break CAS functionality.

If you only have a single-node CAS deployment, there is nothing further for you to do.

# Support
If you have questions on the details this vulnerability and how it might be reproduced, please contact `security@apereo.org` or `cas-appsec-public@apereo.org`.

# Resources

* [Apache Commons statement to widespread Java object de-serialisation vulnerability](https://blogs.apache.org/foundation/entry/apache_commons_statement_to_widespread)
* [Apache Commons Collections security reports](https://commons.apache.org/proper/commons-collections/security-reports.html)

[Misagh Moayyed](https://fawnoos.com)


text:
namespace iMotto.Adapter.Users.Requests
{
    class ModifyUserNameRequest:AuthedRequest
    {
        public string UserName { get; set; }
    }
}


text:
"""
Configuration example. Copy this to
config.py and edit according to your needs
"""

# MySQL host
DB_HOST = "localhost"

# MySQL credentials
DB_USER = "root"
DB_PASS = ""

# MySQL database name
DB_NAME = "bfs-gamma-archiver"

# your MySQL database engine of choice
# (leave "MyISAM" when in doubt)
DB_ENGINE = "MyISAM"

# Entry point URL for bfs download folder
BFS_URL = "http://odlinfo.bfs.de/daten/"

# bfs credentials
FTP_USER = "your_user_name_here"
FTP_PASS = ""


text:
using System.IO;
using Aliyun.OSS.Common.Communication;
using Aliyun.OSS.Model;

namespace Aliyun.OSS.Transform
{
    internal class GetBucketRequestPaymentResultDeserializer : ResponseDeserializer<GetBucketRequestPaymentResult, RequestPaymentConfiguration>
    {
        public GetBucketRequestPaymentResultDeserializer(IDeserializer<Stream, RequestPaymentConfiguration> contentDeserializer)
            : base(contentDeserializer)
        { }

        public override GetBucketRequestPaymentResult Deserialize(ServiceResponse xmlStream)
        {
            GetBucketRequestPaymentResult result = new GetBucketRequestPaymentResult();

            var mode = ContentDeserializer.Deserialize(xmlStream.Content);

            result.Payer = mode.Payer;

            this.DeserializeGeneric(xmlStream, result);
            return result;
        }
    }
}