/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*-
 * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
 * Editor Settings: expandtabs and use 4 spaces for indentation */

/*
 * Copyright Likewise Software
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.  You should have received a copy of the GNU General
 * Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * LIKEWISE SOFTWARE MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING
 * TERMS AS WELL.  IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT
 * WITH LIKEWISE SOFTWARE, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE
 * TERMS OF THAT SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE GNU
 * GENERAL PUBLIC LICENSE, NOTWITHSTANDING THE ABOVE NOTICE.  IF YOU
 * HAVE QUESTIONS, OR WISH TO REQUEST A COPY OF THE ALTERNATE LICENSING
 * TERMS OFFERED BY LIKEWISE SOFTWARE, PLEASE CONTACT LIKEWISE SOFTWARE AT
 * license@likewisesoftware.com
 */

/*
 * Copyright (C) Likewise Software. All rights reserved.
 *
 * Module Name:
 *
 *        ea.c
 *
 * Abstract:
 *
 *        Likewise Posix File System Driver (PVFS)
 *
 *        Query/Set Extended Attributes support.
 *
 *        WARNING: THIS IS A TEST IMPLEMENTATION.  DO NOT USE IN PRODUCTION
 *        ENVIRONMENTS.  THIS IMPLEMENTATION IS LACKING AT LEAST IN THE
 *        FOLLOWING AREAS:
 *
 *        1. pIrp->Flags are not supported when querying ea.
 *
 *        2. PFILE_FULL_EA_INFORMATION::Flags are not supported.
 *
 *        Look at ea_xattr.c for more information.
 *
 * Authors: Evgeny Popovich <epopovich@likewise.com>
 */

#include "pvfs.h"


static
NTSTATUS
PvfsQueryEaEaToFileFullEaInfo(
    IN PSTR pszEaName,
    IN PPVFS_EA_VALUE pEaValue,
    IN OUT PFILE_FULL_EA_INFORMATION pOutBuffer,
    IN ULONG OutBufferLength,
    IN OUT PULONG pBytesUsed,
    IN OUT PFILE_FULL_EA_INFORMATION* ppPrevEaInfo
    );


NTSTATUS
PvfsQueryEa(
    PPVFS_IRP_CONTEXT  pIrpContext
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PIRP pIrp = pIrpContext->pIrp;
    PPVFS_CCB pCcb = NULL;
    PFILE_FULL_EA_INFORMATION pOutBuffer = pIrp->Args.QueryEa.Buffer;
    PFILE_FULL_EA_INFORMATION pPrevEaInfo = NULL;
    ULONG outBufferLength = pIrp->Args.QueryEa.Length;
    ULONG bytesUsed = 0;
    PFILE_GET_EA_INFORMATION pGetEaInfo = pIrp->Args.QueryEa.EaList;
    ULONG getEaInfoLength = pIrp->Args.QueryEa.EaListLength;
    PPVFS_EA_VALUE pEaValuesArray = NULL;
    PSTR* ppszEaNamesArray = NULL;
    ULONG eaArrayLength = 0;
    int i = 0;

    if (!gPvfsDriverState.Config.EnableEaSupport)
    {
        ntStatus = STATUS_EAS_NOT_SUPPORTED;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (!(pIrp->Flags & IRP_IO_FLAG_RESTART_SCAN) ||
        (pIrp->Flags & IRP_IO_FLAG_RETURN_SINGLE_ENTRY) ||
        (pIrp->Flags & IRP_IO_FLAG_USE_INDEX))
    {
        ntStatus = STATUS_NOT_SUPPORTED;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    ntStatus = IoRtlEaCheckGetEaInformation(pGetEaInfo, getEaInfoLength,
                                            IO_EA_NAME_TYPE_WINDOWS, NULL);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus =  PvfsAcquireCCB(pIrp->FileHandle, &pCcb);
    BAIL_ON_NT_STATUS(ntStatus);

    if (!pGetEaInfo)
    {
        ntStatus = PvfsGetFileEasXattr(pCcb, &eaArrayLength, &ppszEaNamesArray,
                                       &pEaValuesArray);
        BAIL_ON_NT_STATUS(ntStatus);

        for (i = 0; i < eaArrayLength; ++i)
        {
            ntStatus = PvfsQueryEaEaToFileFullEaInfo(
                            ppszEaNamesArray[i],
                            &pEaValuesArray[i],
                            pOutBuffer,
                            outBufferLength,
                            &bytesUsed,
                            &pPrevEaInfo);
            BAIL_ON_NT_STATUS(ntStatus);
        }
    }
    else
    {
        while (1)
        {
            PVFS_EA_VALUE eaValue;

            ntStatus = PvfsGetFileEaXattr(pCcb, pGetEaInfo->EaName, &eaValue);
            if (ntStatus == STATUS_NO_EAS_ON_FILE ||
                ntStatus == STATUS_RESOURCE_DATA_NOT_FOUND)
            {
                // The ea name is not found - return value of the length zero
                ntStatus = STATUS_SUCCESS;
                eaValue.ValueLength = 0;
            }
            BAIL_ON_NT_STATUS(ntStatus);

            ntStatus = PvfsQueryEaEaToFileFullEaInfo(
                            pGetEaInfo->EaName,
                            &eaValue,
                            pOutBuffer,
                            outBufferLength,
                            &bytesUsed,
                            &pPrevEaInfo);
            BAIL_ON_NT_STATUS(ntStatus);

            if (pGetEaInfo->NextEntryOffset == 0)
            {
                break;
            }

            pGetEaInfo = (PFILE_GET_EA_INFORMATION)LwRtlOffsetToPointer(
                            pGetEaInfo,
                            pGetEaInfo->NextEntryOffset);
        }
    }

    pIrp->IoStatusBlock.BytesTransferred = bytesUsed;

cleanup:

    if (pCcb)
    {
        PvfsReleaseCCB(pCcb);
    }

    PvfsFreeMemory(OUT_PPVOID(&pEaValuesArray));
    if (ppszEaNamesArray)
    {
        for (i = 0; i < eaArrayLength; ++i)
        {
            LwRtlCStringFree(&ppszEaNamesArray[i]);
        }
        PvfsFreeMemory(OUT_PPVOID(&ppszEaNamesArray));
    }

    return ntStatus;

error:

    pIrp->IoStatusBlock.BytesTransferred = 0;

    goto cleanup;
}

NTSTATUS
PvfsSetEa(
    PPVFS_IRP_CONTEXT pIrpContext
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PIRP pIrp = pIrpContext->pIrp;
    PPVFS_CCB pCcb = NULL;

    ntStatus = PvfsAcquireCCB(pIrp->FileHandle, &pCcb);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus = PvfsSetEaCcb(pCcb, pIrp->Args.SetEa.Buffer,
                            pIrp->Args.SetEa.Length);
    BAIL_ON_NT_STATUS(ntStatus);

cleanup:

    pIrp->IoStatusBlock.BytesTransferred = 0;

    if (pCcb)
    {
        PvfsReleaseCCB(pCcb);
        pCcb = NULL;
    }

    return ntStatus;

error:

    goto cleanup;
}


NTSTATUS
PvfsSetEaCcb(
    IN PPVFS_CCB pCcb,
    IN PFILE_FULL_EA_INFORMATION pFullEaInfo,
    IN ULONG FullEaInfoLength
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;

    if (!gPvfsDriverState.Config.EnableEaSupport)
    {
        ntStatus = STATUS_EAS_NOT_SUPPORTED;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    ntStatus = IoRtlEaCheckFullEaInformation(pFullEaInfo, FullEaInfoLength,
                                             IO_EA_NAME_TYPE_WINDOWS, NULL);
    BAIL_ON_NT_STATUS(ntStatus);

    if (!FullEaInfoLength)
    {
        goto cleanup;
    }

    while (1)
    {
        PVFS_EA_VALUE eaValue;

        if (pFullEaInfo->Flags)
        {
            ntStatus = STATUS_NOT_SUPPORTED;
            BAIL_ON_NT_STATUS(ntStatus);
        }

        if (pFullEaInfo->EaValueLength > PVFS_MAX_EA_VALUE_SIZE)
        {
            ntStatus = STATUS_NOT_SUPPORTED;
            BAIL_ON_NT_STATUS(ntStatus);
        }

        if (!pFullEaInfo->EaValueLength)
        {
            ntStatus = PvfsRemoveFileEaXattr(pCcb, pFullEaInfo->EaName);
            if (ntStatus == STATUS_NO_EAS_ON_FILE ||
                ntStatus == STATUS_RESOURCE_DATA_NOT_FOUND)
            {
                ntStatus = STATUS_SUCCESS;
            }
            BAIL_ON_NT_STATUS(ntStatus);
        }
        else
        {
            eaValue.ValueLength = pFullEaInfo->EaValueLength;
            memcpy(eaValue.Value,
                   pFullEaInfo->EaName + pFullEaInfo->EaNameLength + 1,
                   pFullEaInfo->EaValueLength);

            ntStatus = PvfsSetFileEaXattr(pCcb, pFullEaInfo->EaName, &eaValue);
            BAIL_ON_NT_STATUS(ntStatus);
        }

        if (pFullEaInfo->NextEntryOffset == 0)
        {
            break;
        }

        pFullEaInfo = (PFILE_FULL_EA_INFORMATION)LwRtlOffsetToPointer(
                        pFullEaInfo,
                        pFullEaInfo->NextEntryOffset);
    }

cleanup:

    return ntStatus;

error:

    goto cleanup;
}


static
NTSTATUS
PvfsQueryEaEaToFileFullEaInfo(
    IN PSTR pszEaName,
    IN PPVFS_EA_VALUE pEaValue,
    IN OUT PFILE_FULL_EA_INFORMATION pOutBuffer,
    IN ULONG OutBufferLength,
    IN OUT PULONG pBytesUsed,
    IN OUT PFILE_FULL_EA_INFORMATION* ppPrevEaInfo
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    ULONG bytesUsed = *pBytesUsed;
    PFILE_FULL_EA_INFORMATION pPrevEaInfo = *ppPrevEaInfo;

    ULONG eaNameLength = strlen(pszEaName);
    PFILE_FULL_EA_INFORMATION pNewEaInfo = NULL;
    ULONG bytesRequired = (LW_ALIGN_UP(bytesUsed, 4) - bytesUsed) +
                    sizeof(*pNewEaInfo) + eaNameLength + pEaValue->ValueLength;

    if ((OutBufferLength - bytesUsed) < bytesRequired)
    {
        ntStatus = STATUS_BUFFER_TOO_SMALL;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    pNewEaInfo = (PFILE_FULL_EA_INFORMATION)LwRtlOffsetToPointer(
                    pOutBuffer,
                    LW_ALIGN_UP(bytesUsed, 4));

    pNewEaInfo->NextEntryOffset = 0;
    pNewEaInfo->Flags = 0;
    pNewEaInfo->EaNameLength = eaNameLength;
    pNewEaInfo->EaValueLength = pEaValue->ValueLength;
    memcpy(pNewEaInfo->EaName, pszEaName, eaNameLength + 1);
    if (pEaValue->ValueLength)
    {
        memcpy(pNewEaInfo->EaName + eaNameLength + 1, pEaValue->Value,
               pEaValue->ValueLength);
    }

    if (pPrevEaInfo)
    {
        pPrevEaInfo->NextEntryOffset = LwRtlPointerToOffset(pPrevEaInfo,
                                                            pNewEaInfo);
    }

    pPrevEaInfo = pNewEaInfo;
    bytesUsed += bytesRequired;

cleanup:

    *pBytesUsed = bytesUsed;
    *ppPrevEaInfo = pPrevEaInfo;

    return ntStatus;

error:

    // Do not change the IN OUT params on errors
    bytesUsed = *pBytesUsed;
    pPrevEaInfo = *ppPrevEaInfo;

    goto cleanup;
}
