/* -*- 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
 */

#include "includes.h"

static
NTSTATUS
SrvBuildCloseState(
    PCLOSE_REQUEST_HEADER    pRequestHeader,
    PLWIO_SRV_FILE           pFile,
    PSRV_CLOSE_STATE_SMB_V1* ppCloseState
    );

static
NTSTATUS
SrvBuildCloseResponse(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
VOID
SrvFreeCloseStateHandle(
    HANDLE hState
    );

static
VOID
SrvFreeCloseState(
    PSRV_CLOSE_STATE_SMB_V1 pCloseState
    );

NTSTATUS
SrvProcessCloseAndX(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus     = 0;
    PLWIO_SRV_CONNECTION       pConnection  = pExecContext->pConnection;
    PSRV_EXEC_CONTEXT_SMB_V1   pCtxSmb1     = pExecContext->pProtocolContext;
    PLWIO_SRV_SESSION          pSession     = NULL;
    PLWIO_SRV_TREE             pTree        = NULL;
    PLWIO_SRV_FILE             pFile        = NULL;
    PSRV_CLOSE_STATE_SMB_V1    pCloseState  = NULL;

    pCloseState = (PSRV_CLOSE_STATE_SMB_V1)pCtxSmb1->hState;
    if (pCloseState == NULL)
    {
        ULONG               iMsg         = pCtxSmb1->iMsg;
        PSRV_MESSAGE_SMB_V1 pSmbRequest  = &pCtxSmb1->pRequests[iMsg];
        PBYTE pBuffer          = pSmbRequest->pBuffer + pSmbRequest->usHeaderSize;
        ULONG ulOffset         = pSmbRequest->usHeaderSize;
        ULONG ulBytesAvailable = pSmbRequest->ulMessageSize - pSmbRequest->usHeaderSize;
        PCLOSE_REQUEST_HEADER pRequestHeader = NULL; // Do not free

        ntStatus = SrvConnectionFindSession_SMB_V1(
                        pCtxSmb1,
                        pConnection,
                        pSmbRequest->pHeader->uid,
                        &pSession);
        BAIL_ON_NT_STATUS(ntStatus);

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

        ntStatus = SrvSessionFindTree_SMB_V1(
                        pCtxSmb1,
                        pSession,
                        pSmbRequest->pHeader->tid,
                        &pTree);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = WireUnmarshallCloseRequest(
                        pBuffer,
                        ulBytesAvailable,
                        ulOffset,
                        &pRequestHeader);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SrvTreeFindFile_SMB_V1(
                        pCtxSmb1,
                        pTree,
                        pRequestHeader->fid,
                        &pFile);
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SrvBuildCloseState(
                        pRequestHeader,
                        pFile,
                        &pCloseState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb1->hState = pCloseState;
        pCtxSmb1->pfnStateRelease = &SrvFreeCloseStateHandle;
    }

    switch (pCloseState->stage)
    {
        case SRV_CLOSE_STAGE_SMB_V1_INITIAL:

            SRV_LOG_DEBUG(
                    pExecContext->pLogContext,
                    SMB_PROTOCOL_VERSION_1,
                    pCtxSmb1->pRequests[pCtxSmb1->iMsg].pHeader->command,
                    "Close State: command(%u),uid(%u),mid(%u),pid(%u),tid(%u),"
                    "file-id(%u),last-write-time(%u)",
                    pCtxSmb1->pRequests[pCtxSmb1->iMsg].pHeader->command,
                    pCtxSmb1->pRequests[pCtxSmb1->iMsg].pHeader->uid,
                    pCtxSmb1->pRequests[pCtxSmb1->iMsg].pHeader->mid,
                    SMB_V1_GET_PROCESS_ID(pCtxSmb1->pRequests[pCtxSmb1->iMsg].pHeader),
                    pCtxSmb1->pRequests[pCtxSmb1->iMsg].pHeader->tid,
                    pCloseState->pRequestHeader->fid,
                    pCloseState->pRequestHeader->ulLastWriteTime);

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V1_SET_INFO_COMPLETED;

            switch (pCloseState->pRequestHeader->ulLastWriteTime)
            {
                case 0:
                case (ULONG)-1:

                    break;

                default:

                    ntStatus = WireSMBUTimetoNTTimeLocal(
                                pCloseState->pRequestHeader->ulLastWriteTime,
                                &pCloseState->fileBasicInfo.LastWriteTime);
                    BAIL_ON_NT_STATUS(ntStatus);

                    SrvPrepareExecContextAsync(pExecContext);

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

                    SrvReleaseExecContextAsync(pExecContext);

                    break;
            }

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V1_SET_INFO_COMPLETED:

            switch (pExecContext->ioStatusBlock.Status)
            {
                case STATUS_SUCCESS:

                    break;

                default:

                    LWIO_LOG_ERROR(
                        "Failed to set the last write time for file "
                        " [fid:%u][code:%d]",
                        pCloseState->pFile->fid,
                        pExecContext->ioStatusBlock.Status);

                    break;
            }

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V1_ATTEMPT_CLOSE;

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V1_ATTEMPT_CLOSE:

            SrvFileRundown(pCloseState->pFile);

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V1_DO_IO_RUNDOWN;

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V1_DO_IO_RUNDOWN:

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V1_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_V1_BUILD_RESPONSE:

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

            ntStatus = SrvBuildCloseResponse(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pCloseState->stage = SRV_CLOSE_STAGE_SMB_V1_DONE;

            // intentional fall through

        case SRV_CLOSE_STAGE_SMB_V1_DONE:

            if (pCtxSmb1->pFile)
            {
                SrvFileRelease(pCtxSmb1->pFile);
                pCtxSmb1->pFile = NULL;
            }

            break;
    }

cleanup:

    if (pFile)
    {
        SrvFileRelease(pFile);
    }

    if (pTree)
    {
        SrvTreeRelease(pTree);
    }

    if (pSession)
    {
        SrvSessionRelease(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
SrvBuildCloseState(
    PCLOSE_REQUEST_HEADER    pRequestHeader,
    PLWIO_SRV_FILE           pFile,
    PSRV_CLOSE_STATE_SMB_V1* ppCloseState
    )
{
    NTSTATUS                ntStatus    = STATUS_SUCCESS;
    PSRV_CLOSE_STATE_SMB_V1 pCloseState = NULL;

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

    pCloseState->stage = SRV_CLOSE_STAGE_SMB_V1_INITIAL;

    pCloseState->pRequestHeader = pRequestHeader;

    pCloseState->pFile          = SrvFileAcquire(pFile);

    *ppCloseState = pCloseState;

cleanup:

    return ntStatus;

error:

    *ppCloseState = NULL;

    if (pCloseState)
    {
        SrvFreeCloseState(pCloseState);
    }

    goto cleanup;
}


static
NTSTATUS
SrvBuildCloseResponse(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS ntStatus = 0;
    PLWIO_SRV_CONNECTION       pConnection  = pExecContext->pConnection;
    PSRV_EXEC_CONTEXT_SMB_V1   pCtxSmb1     = pExecContext->pProtocolContext;
    ULONG                      iMsg         = pCtxSmb1->iMsg;
    PSRV_MESSAGE_SMB_V1        pSmbRequest  = &pCtxSmb1->pRequests[iMsg];
    PSRV_MESSAGE_SMB_V1        pSmbResponse = &pCtxSmb1->pResponses[iMsg];
    PCLOSE_RESPONSE_HEADER     pResponseHeader = NULL; // Do not free
    PBYTE pOutBuffer           = pSmbResponse->pBuffer;
    ULONG ulBytesAvailable     = pSmbResponse->ulBytesAvailable;
    ULONG ulOffset             = 0;
    ULONG ulTotalBytesUsed     = 0;

    if (!pSmbResponse->ulSerialNum)
    {
        ntStatus = SrvMarshalHeader_SMB_V1(
                        pOutBuffer,
                        ulOffset,
                        ulBytesAvailable,
                        COM_CLOSE,
                        STATUS_SUCCESS,
                        TRUE,
                        (pSmbRequest->pHeader->flags2 & FLAG2_ERR_STATUS) != 0,
                        pConnection->serverProperties.ulCapabilities,
                        pCtxSmb1->pTree->tid,
                        SMB_V1_GET_PROCESS_ID(pSmbRequest->pHeader),
                        pCtxSmb1->pSession->uid,
                        pSmbRequest->pHeader->mid,
                        &pSmbResponse->pHeader,
                        &pSmbResponse->pWordCount,
                        &pSmbResponse->pAndXHeader,
                        &pSmbResponse->usHeaderSize);
    }
    else
    {
        ntStatus = SrvMarshalHeaderAndX_SMB_V1(
                        pOutBuffer,
                        ulOffset,
                        ulBytesAvailable,
                        COM_CLOSE,
                        &pSmbResponse->pWordCount,
                        &pSmbResponse->pAndXHeader,
                        &pSmbResponse->usHeaderSize);
    }
    BAIL_ON_NT_STATUS(ntStatus);

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

    *pSmbResponse->pWordCount = 0;

    if (ulBytesAvailable < sizeof(CLOSE_RESPONSE_HEADER))
    {
        ntStatus = STATUS_INVALID_BUFFER_SIZE;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    pResponseHeader = (PCLOSE_RESPONSE_HEADER)pOutBuffer;

    // pOutBuffer       += sizeof(CLOSE_RESPONSE_HEADER);
    // ulOffset         += sizeof(CLOSE_RESPONSE_HEADER);
    // ulBytesAvailable -= sizeof(CLOSE_RESPONSE_HEADER);
    ulTotalBytesUsed += sizeof(CLOSE_RESPONSE_HEADER);

    pResponseHeader->byteCount = 0;

    pSmbResponse->ulMessageSize = ulTotalBytesUsed;

cleanup:

    return ntStatus;

error:

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

    pSmbResponse->ulMessageSize = 0;

    goto cleanup;
}

VOID
SrvCancelFileAsyncOperations(
    PLWIO_SRV_FILE pFile
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    BOOLEAN  bInLock  = FALSE;
    PSRV_BYTE_RANGE_LOCK_STATE_LIST pBRLStateList =
            (PSRV_BYTE_RANGE_LOCK_STATE_LIST)pFile->hCancellableBRLStateList;
    PSRV_BYTE_RANGE_LOCK_STATE pCursor     = NULL;
    PLWIO_ASYNC_STATE          pAsyncState = NULL;

    if (pBRLStateList)
    {
        for(;;)
        {
            if (pCursor)
            {
                SrvFreeMemory(pCursor);
                pCursor = NULL;
            }

            LWIO_LOCK_MUTEX(bInLock, &pBRLStateList->mutex);

            if (pBRLStateList->pHead)
            {
                pCursor = pBRLStateList->pHead;
                pBRLStateList->pHead = pCursor->pNext;
                if (pCursor->pNext == NULL)
                {
                    pBRLStateList->pTail = NULL;
                }
            }
            else
            {
                break;
            }

            LWIO_UNLOCK_MUTEX(bInLock, &pBRLStateList->mutex);

            if (pAsyncState)
            {
                SrvAsyncStateRelease(pAsyncState);

                pAsyncState = NULL;
            }

            ntStatus = SrvTreeFindAsyncState(
                            pFile->pTree,
                            pCursor->ullAsyncId,
                            &pAsyncState);
            if (ntStatus == STATUS_NOT_FOUND)
            {
                ntStatus = STATUS_SUCCESS;

                continue;
            }
            BAIL_ON_NT_STATUS(ntStatus);

            SrvAsyncStateCancel(pAsyncState);
        }
    }

cleanup:

    LWIO_UNLOCK_MUTEX(bInLock, &pBRLStateList->mutex);

    if (pAsyncState)
    {
        SrvAsyncStateRelease(pAsyncState);
    }

    if (pCursor)
    {
        SrvFreeMemory(pCursor);
    }

    return;

error:

    LWIO_LOG_ERROR("File async operation cancellation failed [status: %s = 0x%08X (%d)]",
                   LwNtStatusToName(ntStatus),
                   ntStatus,
                   ntStatus);

    goto cleanup;
}

static
VOID
SrvFreeCloseStateHandle(
    HANDLE hState
    )
{
    SrvFreeCloseState(hState);
}

static
VOID
SrvFreeCloseState(
    PSRV_CLOSE_STATE_SMB_V1 pCloseState
    )
{
    if (pCloseState->pFile)
    {
        SrvFileRelease(pCloseState->pFile);
    }

    SrvFreeMemory(pCloseState);
}
