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

#include "includes.h"

static
NTSTATUS
SrvBuildCloseState_SMB_V2(
    PSMB2_CLOSE_REQUEST_HEADER pRequestHeader,
    PLWIO_SRV_TREE_2           pTree,
    PLWIO_SRV_FILE_2           pFile,
    PSRV_CLOSE_STATE_SMB_V2*   ppCloseState
    );

static
NTSTATUS
SrvGetFileInformation_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
NTSTATUS
SrvBuildCloseResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
VOID
SrvFreeCloseStateHandle_SMB_V2(
    HANDLE hCloseState
    );

static
VOID
SrvFreeCloseState_SMB_V2(
    PSRV_CLOSE_STATE_SMB_V2 pCloseState
    );

NTSTATUS
SrvProcessClose_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus    = STATUS_SUCCESS;
    PLWIO_SRV_CONNECTION       pConnection = pExecContext->pConnection;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2    = pExecContext->pProtocolContext;
    ULONG                      iMsg        = pCtxSmb2->iMsg;
    PSRV_MESSAGE_SMB_V2        pSmbRequest = &pCtxSmb2->pRequests[iMsg];
    PSRV_CLOSE_STATE_SMB_V2    pCloseState = pCtxSmb2->hState;
    PLWIO_SRV_SESSION_2        pSession    = NULL;
    PLWIO_SRV_TREE_2           pTree       = NULL;
    PLWIO_SRV_FILE_2           pFile       = NULL;

    if (pCloseState == NULL)
    {
        PSMB2_CLOSE_REQUEST_HEADER pRequestHeader = NULL; // Do not free

        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 = SMB2UnmarshalCloseRequest(pSmbRequest, &pRequestHeader);
        BAIL_ON_NT_STATUS(ntStatus);

        SRV_LOG_DEBUG(
                pExecContext->pLogContext,
                SMB_PROTOCOL_VERSION_2,
                pSmbRequest->pHeader->command,
                "Close request: "
                "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),close-flags(0x%x)",
                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->usFlags);

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

        ntStatus = SrvBuildCloseState_SMB_V2(
                        pRequestHeader,
                        pTree,
                        pFile,
                        &pCloseState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb2->hState = pCloseState;
        pCtxSmb2->pfnStateRelease = &SrvFreeCloseStateHandle_SMB_V2;
    }

    switch (pCloseState->stage)
    {
        case SRV_CLOSE_STAGE_SMB_V2_INITIAL:

            if (pCloseState->pRequestHeader->usFlags &
                    SMB2_CLOSE_FLAGS_GET_FILE_ATTRIBUTES)
            {
                ntStatus = SrvGetFileInformation_SMB_V2(pExecContext);
                BAIL_ON_NT_STATUS(ntStatus);
            }

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V2_ATTEMPT_IO;

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V2_ATTEMPT_IO:

            SrvFile2SetClosing(pCloseState->pFile);
            SrvFile2Rundown(pCloseState->pFile);

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V2_DO_IO_RUNDOWN;

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V2_DO_IO_RUNDOWN:

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V2_BUILD_RESPONSE;

            SrvPrepareExecContextAsync(pExecContext);

            ntStatus = IoRundownFile(pCloseState->pFile->hFile,
                                     pExecContext->pAcb,
                                     &pExecContext->ioStatusBlock);
            if (ntStatus == STATUS_PENDING)
            {
                BAIL_ON_NT_STATUS(ntStatus);
            }

            SrvReleaseExecContextAsync(pExecContext);

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V2_BUILD_RESPONSE:

            ntStatus = pExecContext->ioStatusBlock.Status;
            BAIL_ON_NT_STATUS(ntStatus);

            ntStatus = SrvBuildCloseResponse_SMB_V2(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V2_DONE;

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V2_DONE:

            if (pCtxSmb2->pFile)
            {
                SrvFile2Release(pCtxSmb2->pFile);
                pCtxSmb2->pFile = NULL;
            }

            break;
    }

cleanup:

    if (pFile)
    {
        SrvFile2Release(pFile);
    }

    if (pTree)
    {
        SrvTree2Release(pTree);
    }

    if (pSession)
    {
        SrvSession2Release(pSession);
    }

    // If the file was successfully opened then any attempt to close, 
    // even if unsuccessful, should cause successive closes on the same 
    // chain to fail.
    if (pCtxSmb2->FileOpenStatus == STATUS_SUCCESS) 
    {
        pCtxSmb2->FileOpenStatus = STATUS_FILE_CLOSED;
    }

    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
SrvBuildCloseState_SMB_V2(
    PSMB2_CLOSE_REQUEST_HEADER pRequestHeader,
    PLWIO_SRV_TREE_2           pTree,
    PLWIO_SRV_FILE_2           pFile,
    PSRV_CLOSE_STATE_SMB_V2*   ppCloseState
    )
{
    NTSTATUS                ntStatus    = STATUS_SUCCESS;
    PSRV_CLOSE_STATE_SMB_V2 pCloseState = NULL;

    ntStatus = SrvAllocateMemory(
                    sizeof(SRV_CLOSE_STATE_SMB_V2),
                    (PVOID*)&pCloseState);
    BAIL_ON_NT_STATUS(ntStatus);

    pCloseState->pRequestHeader = pRequestHeader;

    pCloseState->pTree = SrvTree2Acquire(pTree);

    pCloseState->pFile = SrvFile2Acquire(pFile);

    *ppCloseState = pCloseState;

cleanup:

    return ntStatus;

error:

    *ppCloseState = NULL;

    if (pCloseState)
    {
        SrvFreeCloseState_SMB_V2(pCloseState);
    }

    goto cleanup;
}

static
NTSTATUS
SrvGetFileInformation_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus    = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2    = pExecContext->pProtocolContext;
    PSRV_CLOSE_STATE_SMB_V2    pCloseState = pCtxSmb2->hState;

    ntStatus = pExecContext->ioStatusBlock.Status;
    BAIL_ON_NT_STATUS(ntStatus);

    if (!pCloseState->pFileBasicInfo)
    {
        pCloseState->pFileBasicInfo = &pCloseState->fileBasicInfo;

        SrvPrepareExecContextAsync(pExecContext);

        ntStatus = IoQueryInformationFile(
                        pCloseState->pFile->hFile,
                        pExecContext->pAcb,
                        &pExecContext->ioStatusBlock,
                        pCloseState->pFileBasicInfo,
                        sizeof(pCloseState->fileBasicInfo),
                        FileBasicInformation);
        BAIL_ON_NT_STATUS(ntStatus);

        SrvReleaseExecContextAsync(pExecContext);
    }

    if (!pCloseState->pFileStdInfo)
    {
        pCloseState->pFileStdInfo = &pCloseState->fileStdInfo;

        SrvPrepareExecContextAsync(pExecContext);

        ntStatus = IoQueryInformationFile(
                        pCloseState->pFile->hFile,
                        pExecContext->pAcb,
                        &pExecContext->ioStatusBlock,
                        pCloseState->pFileStdInfo,
                        sizeof(pCloseState->fileStdInfo),
                        FileStandardInformation);
        BAIL_ON_NT_STATUS(ntStatus);

        SrvReleaseExecContextAsync(pExecContext);
    }

error:

    return ntStatus;
}

static
NTSTATUS
SrvBuildCloseResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus     = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2     = pExecContext->pProtocolContext;
    PSRV_CLOSE_STATE_SMB_V2    pCloseState  = NULL;
    ULONG                      iMsg         = pCtxSmb2->iMsg;
    PSRV_MESSAGE_SMB_V2        pSmbRequest  = &pCtxSmb2->pRequests[iMsg];
    PSRV_MESSAGE_SMB_V2        pSmbResponse = &pCtxSmb2->pResponses[iMsg];
    PSMB2_CLOSE_RESPONSE_HEADER pResponseHeader = NULL; // Do not free
    PBYTE  pOutBuffer       = pSmbResponse->pBuffer;
    ULONG  ulOffset         = 0;
    ULONG  ulTotalBytesUsed = 0;
    ULONG  ulBytesUsed      = 0;
    ULONG  ulBytesAvailable = pSmbResponse->ulBytesAvailable;

    pCloseState = pCtxSmb2->hState;

    ntStatus = SMB2MarshalHeader(
                    pOutBuffer,
                    ulOffset,
                    ulBytesAvailable,
                    COM2_CLOSE,
                    pSmbRequest->CreditCharge,
                    pExecContext->usCreditsGranted,
                    pSmbRequest->pHeader->ulPid,
                    pSmbRequest->pHeader->ullCommandSequence,
                    pCtxSmb2->pTree->ulTid,
                    pCtxSmb2->pSession->ullUid,
                    0LL, /* Async Id */
                    STATUS_SUCCESS,
                    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;

    if (ulBytesAvailable < sizeof(SMB2_CLOSE_RESPONSE_HEADER))
    {
        ntStatus = STATUS_INVALID_NETWORK_RESPONSE;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    pResponseHeader = (PSMB2_CLOSE_RESPONSE_HEADER)pOutBuffer;
    memset(pResponseHeader, 0, sizeof(*pResponseHeader));

    pOutBuffer       += sizeof(SMB2_CLOSE_RESPONSE_HEADER);
    ulBytesUsed       = sizeof(SMB2_CLOSE_RESPONSE_HEADER);
    ulOffset         += sizeof(SMB2_CLOSE_RESPONSE_HEADER);
    ulBytesAvailable -= sizeof(SMB2_CLOSE_RESPONSE_HEADER);
    ulTotalBytesUsed += sizeof(SMB2_CLOSE_RESPONSE_HEADER);

    if (pCloseState->pRequestHeader->usFlags &
            SMB2_CLOSE_FLAGS_GET_FILE_ATTRIBUTES)
    {
        pResponseHeader->ullCreationTime   =
                        pCloseState->fileBasicInfo.CreationTime;
        pResponseHeader->ullLastAccessTime =
                        pCloseState->fileBasicInfo.LastAccessTime;
        pResponseHeader->ullLastWriteTime  =
                        pCloseState->fileBasicInfo.LastWriteTime;
        pResponseHeader->ullLastChangeTime =
                        pCloseState->fileBasicInfo.ChangeTime;
        pResponseHeader->ulFileAttributes  =
                        pCloseState->fileBasicInfo.FileAttributes;
        pResponseHeader->ullAllocationSize =
                        pCloseState->fileStdInfo.AllocationSize;
        pResponseHeader->ullEndOfFile      =
                        pCloseState->fileStdInfo.EndOfFile;

        pResponseHeader->usFlags |= SMB2_CLOSE_FLAGS_GET_FILE_ATTRIBUTES;
    }

    pResponseHeader->usLength          = ulBytesUsed;

    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
SrvFreeCloseStateHandle_SMB_V2(
    HANDLE hCloseState
    )
{
    return SrvFreeCloseState_SMB_V2(hCloseState);
}

static
VOID
SrvFreeCloseState_SMB_V2(
    PSRV_CLOSE_STATE_SMB_V2 pCloseState
    )
{
    if (pCloseState->pFile)
    {
        SrvFile2Release(pCloseState->pFile);
    }

    if (pCloseState->pTree)
    {
        SrvTree2Release(pCloseState->pTree);
    }

    SrvFreeMemory(pCloseState);
}
