/* -*- 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:
 *
 *        queryinfo.c
 *
 * Abstract:
 *
 *        Likewise IO (LWIO) - SRV
 *
 *        Protocols API - SMBV2
 *
 *        Query Information
 *
 * Authors: Krishna Ganugapati (kganugapati@likewise.com)
 *          Sriram Nambakam (snambakam@likewise.com)
 *
 *
 */

#include "includes.h"

static
NTSTATUS
SrvBuildGetInfoState_SMB_V2(
    PSMB2_GET_INFO_REQUEST_HEADER pRequestHeader,
    PSRV_EXEC_CONTEXT             pExecContext,
    PLWIO_SRV_FILE_2              pFile,
    PBYTE                         pInputBuffer,
    ULONG                         ulInputBufferLength,
    PSRV_GET_INFO_STATE_SMB_V2*   ppGetInfoState
    );

static
NTSTATUS
SrvQueryInfo_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
NTSTATUS
SrvBuildGetInfoResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static NTSTATUS
SrvBuildTableInfoResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext,
    GET_INFO_CLASS_DISPATCH_ENTRY *Table,
    size_t TableNumElements
    );

static
VOID
SrvFreeGetInfoStateHandle_SMB_V2(
    HANDLE hGetInfoState
    );

static
VOID
SrvFreeGetInfoState_SMB_V2(
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState
    );

NTSTATUS
SrvProcessGetInfo_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus      = STATUS_SUCCESS;
    PLWIO_SRV_CONNECTION       pConnection   = pExecContext->pConnection;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = pCtxSmb2->hState;
    PLWIO_SRV_SESSION_2        pSession      = NULL;
    PLWIO_SRV_TREE_2           pTree         = NULL;
    PLWIO_SRV_FILE_2           pFile         = NULL;

    if (pGetInfoState == NULL)
    {
        ULONG                      iMsg          = pCtxSmb2->iMsg;
        PSRV_MESSAGE_SMB_V2        pSmbRequest   = &pCtxSmb2->pRequests[iMsg];
        PSMB2_GET_INFO_REQUEST_HEADER pRequestHeader = NULL; // Do not free
        PBYTE                      pInputBuffer  = NULL;
        ULONG                      ulInputBufferLength = 0;

        ntStatus = SrvConnection2FindSession_SMB_V2(
                        pCtxSmb2,
                        pConnection,
                        pSmbRequest->pHeader->ullSessionId,
                        &pSession);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SrvSetStatSession2Info(pExecContext, pSession);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SrvSession2FindTree_SMB_V2(
                        pCtxSmb2,
                        pSession,
                        pSmbRequest->pHeader->ulTid,
                        &pTree);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SMB2UnmarshalGetInfoRequest(
                        pSmbRequest,
                        &pRequestHeader,
                        &pInputBuffer,
                        &ulInputBufferLength);
        BAIL_ON_NT_STATUS(ntStatus);

        SRV_LOG_DEBUG(
                pExecContext->pLogContext,
                SMB_PROTOCOL_VERSION_2,
                pSmbRequest->pHeader->command,
                "Get Info request params: "
                "command(%u),uid(%llu),cmd-seq(%llu),pid(%u),tid(%u),"
                "credits(%u),flags(0x%x),chain-offset(%u),"
                "file-id(persistent:0x%x,volatile:0x%x),"
                "info-class(0x%x),info-type(0x%x),flags(0x%x),"
                "input-buffer-length(%u),input-buffer-offset(%u),"
                "output-buffer-length(%u),additional-info(%u)",
                pSmbRequest->pHeader->command,
                (long long)pSmbRequest->pHeader->ullSessionId,
                (long long)pSmbRequest->pHeader->ullCommandSequence,
                pSmbRequest->pHeader->ulPid,
                pSmbRequest->pHeader->ulTid,
                pSmbRequest->pHeader->Credits,
                pSmbRequest->pHeader->ulFlags,
                pSmbRequest->pHeader->ulChainOffset,
                (long long)pRequestHeader->fid.ullPersistentId,
                (long long)pRequestHeader->fid.ullVolatileId,
                pRequestHeader->ucInfoClass,
                pRequestHeader->ucInfoType,
                pRequestHeader->ulFlags,
                pRequestHeader->ulInputBufferLen,
                pRequestHeader->usInputBufferOffset,
                pRequestHeader->ulOutputBufferLen,
                pRequestHeader->ulAdditionalInfo);

        ntStatus = SrvTree2FindFile_SMB_V2(
                            pCtxSmb2,
                            pTree,
                            &pRequestHeader->fid,
                            &pFile);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SrvBuildGetInfoState_SMB_V2(
                            pRequestHeader,
                            pExecContext,
                            pFile,
                            pInputBuffer,
                            ulInputBufferLength,
                            &pGetInfoState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb2->hState = pGetInfoState;
        pCtxSmb2->pfnStateRelease = &SrvFreeGetInfoStateHandle_SMB_V2;
    }

    switch (pGetInfoState->stage)
    {
        case SRV_GET_INFO_STAGE_SMB_V2_INITIAL:

            pGetInfoState->stage = SRV_GET_INFO_STAGE_SMB_V2_ATTEMPT_IO;

            // Intentional fall through

        case SRV_GET_INFO_STAGE_SMB_V2_ATTEMPT_IO:

            ntStatus = SrvQueryInfo_SMB_V2(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pGetInfoState->stage = SRV_GET_INFO_STAGE_SMB_V2_BUILD_RESPONSE;

            // Intentional fall through

        case SRV_GET_INFO_STAGE_SMB_V2_BUILD_RESPONSE:

            ntStatus = SrvBuildGetInfoResponse_SMB_V2(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pGetInfoState->stage = SRV_GET_INFO_STAGE_SMB_V2_DONE;

            // Intentional fall through

        case SRV_GET_INFO_STAGE_SMB_V2_DONE:

            break;
    }

cleanup:

    if (pFile)
    {
        SrvFile2Release(pFile);
    }

    if (pTree)
    {
        SrvTree2Release(pTree);
    }

    if (pSession)
    {
        SrvSession2Release(pSession);
    }

    return ntStatus;

error:

    switch (ntStatus)
    {
        case STATUS_PENDING:

            // TODO: Add an indicator to the file object to trigger a
            //       cleanup if the connection gets closed and all the
            //       files involved have to be closed

            break;

        default:

            SrvReleaseExecContextAsync(pExecContext);

            break;
    }

    goto cleanup;
}

static
NTSTATUS
SrvBuildGetInfoState_SMB_V2(
    PSMB2_GET_INFO_REQUEST_HEADER pRequestHeader,
    PSRV_EXEC_CONTEXT             pExecContext,
    PLWIO_SRV_FILE_2              pFile,
    PBYTE                         pInputBuffer,
    ULONG                         ulInputBufferLength,
    PSRV_GET_INFO_STATE_SMB_V2*   ppGetInfoState
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = NULL;

    ntStatus = SrvAllocateMemory(
                    sizeof(SRV_GET_INFO_STATE_SMB_V2),
                    (PVOID*)&pGetInfoState);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus = SrvInitProcessInfoState(
                    &pGetInfoState->infoState,
                    pFile->hFile,
                    pRequestHeader->ulOutputBufferLen,
                    pRequestHeader->ucInfoClass);
    BAIL_ON_NT_STATUS(ntStatus);

    pGetInfoState->stage = SRV_GET_INFO_STAGE_SMB_V2_INITIAL;

    pGetInfoState->pRequestHeader = pRequestHeader;

    pGetInfoState->pFile = SrvFile2Acquire(pFile);

    pGetInfoState->pInputBuffer = pInputBuffer;

    pGetInfoState->ulInputBufferLength = ulInputBufferLength;

    *ppGetInfoState = pGetInfoState;

cleanup:

    return ntStatus;

error:

    *ppGetInfoState = NULL;

    if (pGetInfoState)
    {
        SrvFreeGetInfoState_SMB_V2(pGetInfoState);
    }

    goto cleanup;
}

static
NTSTATUS
SrvQueryInfo_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus      = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = pCtxSmb2->hState;

    switch (pGetInfoState->pRequestHeader->ucInfoType)
    {
        case SMB2_INFO_TYPE_FILE:

            ntStatus = SrvGetTableInfo(
                            pExecContext,
                            &pGetInfoState->infoState,
                            SrvGetFileInfoDispatchTable_SMB_V2(),
                            SrvGetFileInfoDispatchTableSize_SMB_V2()
                            );

            break;

        case SMB2_INFO_TYPE_FILE_SYSTEM:

            ntStatus = SrvGetTableInfo(
                            pExecContext,
                            &pGetInfoState->infoState,
                            SrvGetFileSystemInfoDispatchTable_SMB_V2(),
                            SrvGetFileSystemInfoDispatchTableSize_SMB_V2()
                            );

            break;

        case SMB2_INFO_TYPE_SECURITY:

            ntStatus = SrvGetSecurityInfo_SMB_V2(pExecContext);

            break;

        case SMB2_INFO_TYPE_QUOTA:

            ntStatus = SrvGetQuotaInfo_SMB_V2(pExecContext);

            break;

        default:

            ntStatus = STATUS_INVALID_INFO_CLASS;

            break;
    }

    return ntStatus;
}

static
NTSTATUS
SrvBuildGetInfoResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = pCtxSmb2->hState;

    switch (pGetInfoState->pRequestHeader->ucInfoType)
    {
        case SMB2_INFO_TYPE_FILE:
            ntStatus = SrvBuildTableInfoResponse_SMB_V2(
                            pExecContext,
                            SrvGetFileInfoDispatchTable_SMB_V2(),
                            SrvGetFileInfoDispatchTableSize_SMB_V2()
                            );

            break;

        case SMB2_INFO_TYPE_FILE_SYSTEM:

            ntStatus = SrvBuildTableInfoResponse_SMB_V2(
                            pExecContext,
                            SrvGetFileSystemInfoDispatchTable_SMB_V2(),
                            SrvGetFileSystemInfoDispatchTableSize_SMB_V2()
                            );
            break;

        case SMB2_INFO_TYPE_SECURITY:

            ntStatus = SrvBuildSecurityInfoResponse_SMB_V2(pExecContext);

            break;

        case SMB2_INFO_TYPE_QUOTA:

            ntStatus = SrvBuildQuotaInfoResponse_SMB_V2(pExecContext);

            break;

        default:

            ntStatus = STATUS_INVALID_INFO_CLASS;

            break;
    }

    return ntStatus;
}

static NTSTATUS
SrvBuildTableInfoResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext,
    GET_INFO_CLASS_DISPATCH_ENTRY *Table,
    size_t TableNumElements
    )
{
    NTSTATUS                   ntStatus      = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = pCtxSmb2->hState;
    PSRV_PROCESS_INFO_STATE    pInfoState    = &pGetInfoState->infoState;
    ULONG ulOutputBufferLen = pGetInfoState->pRequestHeader->ulOutputBufferLen;
    UCHAR ucInfoClass = pGetInfoState->pRequestHeader->ucInfoClass;
    PGET_INFO_CLASS_DISPATCH_ENTRY pInfoEntry = Table + ucInfoClass;
    ULONG                      iMsg          = pCtxSmb2->iMsg;
    PSRV_MESSAGE_SMB_V2        pSmbRequest   = &pCtxSmb2->pRequests[iMsg];
    PSRV_MESSAGE_SMB_V2        pSmbResponse  = &pCtxSmb2->pResponses[iMsg];
    PBYTE pOutBuffer         = pSmbResponse->pBuffer;
    ULONG ulBytesAvailable   = pSmbResponse->ulBytesAvailable;
    ULONG ulOffset           = 0;
    ULONG ulTotalBytesUsed   = 0;
    ULONG ulMarshalBytesUsed = 0;
    PSMB2_GET_INFO_RESPONSE_HEADER pGetInfoResponseHeader = NULL;

    if (ucInfoClass >= TableNumElements || !pInfoEntry->GetHandler)
    {
        ntStatus = STATUS_INVALID_INFO_CLASS;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    ntStatus = SMB2MarshalHeader(
                    pOutBuffer,
                    ulOffset,
                    ulBytesAvailable,
                    COM2_GETINFO,
                    pSmbRequest->CreditCharge,
                    pExecContext->usCreditsGranted,
                    pSmbRequest->pHeader->ulPid,
                    pSmbRequest->pHeader->ullCommandSequence,
                    pCtxSmb2->pTree->ulTid,
                    pCtxSmb2->pSession->ullUid,
                    0LL,
                    pExecContext->ioStatusBlock.Status,
                    TRUE,
                    LwIsSetFlag(
                        pSmbRequest->pHeader->ulFlags,
                        SMB2_FLAGS_RELATED_OPERATION),
                    &pSmbResponse->pHeader,
                    &pSmbResponse->ulHeaderSize);
    BAIL_ON_NT_STATUS(ntStatus);

    pOutBuffer       += pSmbResponse->ulHeaderSize;
    ulOffset         += pSmbResponse->ulHeaderSize;
    ulBytesAvailable -= pSmbResponse->ulHeaderSize;
    ulTotalBytesUsed += pSmbResponse->ulHeaderSize;

    /* Limit marshaling space to the space allocated by the client. */
    if (ulBytesAvailable < sizeof(*pGetInfoResponseHeader) + ulOutputBufferLen)
    {
        ntStatus = STATUS_INVALID_BUFFER_SIZE;
        BAIL_ON_NT_STATUS(ntStatus);
    }
    ulBytesAvailable = sizeof(*pGetInfoResponseHeader) + ulOutputBufferLen;

    /*
     * The get should have rejected any request that didn't allocate at
     * least enough space for the fixed portion of any info request.
     */
    LW_ASSERT(ulBytesAvailable >= pInfoEntry->ProtoStructSize);

    pGetInfoResponseHeader = (PSMB2_GET_INFO_RESPONSE_HEADER)pOutBuffer;

    pOutBuffer       += sizeof(*pGetInfoResponseHeader);
    ulOffset         += sizeof(*pGetInfoResponseHeader);
    ulBytesAvailable -= sizeof(*pGetInfoResponseHeader);
    ulTotalBytesUsed += sizeof(*pGetInfoResponseHeader);

    pGetInfoResponseHeader->usLength = sizeof(*pGetInfoResponseHeader) + 1;
    pGetInfoResponseHeader->usOutBufferOffset = ulOffset;

    ntStatus = pInfoEntry->MarshalHandler(
                    pExecContext,
                    pInfoState,
                    pInfoEntry,
                    pOutBuffer,
                    ulBytesAvailable,
                    &ulMarshalBytesUsed);
    BAIL_ON_NT_STATUS(ntStatus);

    pGetInfoResponseHeader->ulOutBufferLength = ulMarshalBytesUsed;

    ulTotalBytesUsed += pGetInfoResponseHeader->ulOutBufferLength;
    pSmbResponse->ulMessageSize = ulTotalBytesUsed;

cleanup:

    return ntStatus;

error:

    if (ulTotalBytesUsed)
    {
        pSmbResponse->pHeader = NULL;
        pSmbResponse->ulHeaderSize = 0;
        memset(pSmbResponse->pBuffer, 0, ulTotalBytesUsed);
    }

    pSmbResponse->ulMessageSize = 0;

    goto cleanup;
}

static
VOID
SrvFreeGetInfoStateHandle_SMB_V2(
    HANDLE hGetInfoState
    )
{
    return SrvFreeGetInfoState_SMB_V2(hGetInfoState);
}

static
VOID
SrvFreeGetInfoState_SMB_V2(
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState
    )
{
    SrvFiniProcessInfoState(&pGetInfoState->infoState);

    if (pGetInfoState->pFile)
    {
        SrvFile2Release(pGetInfoState->pFile);
    }

    SrvFreeMemory(pGetInfoState);
}
