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

#include "includes.h"

static
NTSTATUS
SrvBuildLockRequestState_SMB_V2(
    PSRV_EXEC_CONTEXT               pExecContext,
    PSMB2_LOCK_REQUEST_HEADER       pLockRequestHeader,
    PLWIO_SRV_TREE_2                pTree,
    PLWIO_SRV_FILE_2                pFile,
    PSRV_LOCK_REQUEST_STATE_SMB_V2* ppLockRequestState
    );

static
NTSTATUS
SrvProcessLockRequest_SMB_V2(
    PSRV_EXEC_CONTEXT              pExecContext,
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState
    );

static
NTSTATUS
SrvValidateLockRequest_SMB_V2(
    PSMB2_LOCK pLock,
    BOOLEAN    bLocking,
    USHORT     usLockCount
    );

static
VOID
SrvClearLocks_SMB_V2(
    PSRV_EXEC_CONTEXT              pExecContext,
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState
    );

static
NTSTATUS
SrvBuildLockResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
VOID
SrvFreeLockRequestStateHandle_SMB_V2(
    HANDLE hLockRequestState
    );

static
VOID
SrvFreeLockRequestState_SMB_V2(
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState
    );

NTSTATUS
SrvProcessLock_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];
    PSMB2_LOCK_REQUEST_HEADER  pRequestHeader = NULL; // Do not free
    PLWIO_SRV_SESSION_2        pSession       = NULL;
    PLWIO_SRV_TREE_2           pTree          = NULL;
    PLWIO_SRV_FILE_2           pFile          = NULL;
    PLWIO_ASYNC_STATE          pAsyncState    = NULL;
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState = pCtxSmb2->hState;

    if (pLockRequestState == NULL)
    {
        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 = SMB2UnmarshalLockRequest(pSmbRequest, &pRequestHeader);
        BAIL_ON_NT_STATUS(ntStatus);

        SRV_LOG_DEBUG(
                pExecContext->pLogContext,
                SMB_PROTOCOL_VERSION_2,
                pSmbRequest->pHeader->command,
                "Lock 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),"
                "lock-sequence(%u),lock-count(%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->ulLockSequence,
                pRequestHeader->usLockCount);

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

        ntStatus = SrvConnection2CreateAsyncState(
                                pConnection,
                                COM2_LOCK,
                                pSmbRequest->pHeader->ullCommandSequence,
                                &SrvCancelExecContextHandle,
                                &SrvReleaseExecContextHandle,
                                &pAsyncState);
        BAIL_ON_NT_STATUS(ntStatus);

        pExecContext->ullAsyncId = pAsyncState->ullAsyncId;

        ntStatus = SrvBuildLockRequestState_SMB_V2(
                            pExecContext,
                            pRequestHeader,
                            pTree,
                            pFile,
                            &pLockRequestState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb2->hState = pLockRequestState;
        pCtxSmb2->pfnStateRelease = &SrvFreeLockRequestStateHandle_SMB_V2;

        pAsyncState->hAsyncState = SrvAcquireExecContext(pExecContext);
    }

    switch (pLockRequestState->stage)
    {
        case SRV_LOCK_STAGE_SMB_V2_INITIAL:

            pLockRequestState->stage = SRV_LOCK_STAGE_SMB_V2_ATTEMPT_LOCK;

            // intentional fall through

        case SRV_LOCK_STAGE_SMB_V2_ATTEMPT_LOCK:

            ntStatus = SrvProcessLockRequest_SMB_V2(
                                pExecContext,
                                pLockRequestState);
            if ((ntStatus == STATUS_CANCELLED) &&
                !pLockRequestState->bCancelledByClient)
            {
                if (pLockRequestState->pFile &&
                    SrvFile2IsFileClosing(pLockRequestState->pFile))
                {
                    ntStatus = STATUS_RANGE_NOT_LOCKED;
                }
                else
                {
                    SrvClearLocks_SMB_V2(pExecContext, pLockRequestState);

                    // could be due to tree disconnect or logoff
                    ntStatus = STATUS_SUCCESS;
                }
            }
            BAIL_ON_NT_STATUS(ntStatus);

            pLockRequestState->stage = SRV_LOCK_STAGE_SMB_V2_BUILD_RESPONSE;

            // intentional fall through

        case SRV_LOCK_STAGE_SMB_V2_BUILD_RESPONSE:

            ntStatus = SrvBuildLockResponse_SMB_V2(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pLockRequestState->stage = SRV_LOCK_STAGE_SMB_V2_DONE;

            // intentional fall through

        case SRV_LOCK_STAGE_SMB_V2_DONE:

            break;
    }

cleanup:

    if (pFile)
    {
        SrvFile2Release(pFile);
    }

    if (pTree)
    {
        SrvTree2Release(pTree);
    }

    if (pSession)
    {
        SrvSession2Release(pSession);
    }

    if (pAsyncState)
    {
        SrvAsyncStateRelease(pAsyncState);
    }

    return ntStatus;

error:

    switch (ntStatus)
    {
        case STATUS_PENDING:

            if (!pExecContext->bInterimSent)
            {
                NTSTATUS ntStatus2 = SrvInterimResponse_SMB_V2(pExecContext);
                if (ntStatus2 != STATUS_SUCCESS)
                {
                    LWIO_LOG_ERROR(
                            "Failed to create interim response [code:0x%8x]",
                            ntStatus2);
                }
            }

            break;

        case STATUS_NETWORK_NAME_DELETED:
        case STATUS_USER_SESSION_DELETED:

            ntStatus = STATUS_FILE_CLOSED;

            // intentional fall through

        default:

            if (ntStatus == STATUS_FILE_LOCK_CONFLICT)
            {
                ntStatus = STATUS_LOCK_NOT_GRANTED;
            }

            if (pLockRequestState)
            {
                SrvClearLocks_SMB_V2(pExecContext, pLockRequestState);

                SrvReleaseExecContextAsync(pExecContext);
            }

            break;
    }

    goto cleanup;
}

static
NTSTATUS
SrvBuildLockRequestState_SMB_V2(
    PSRV_EXEC_CONTEXT               pExecContext,
    PSMB2_LOCK_REQUEST_HEADER       pLockRequestHeader,
    PLWIO_SRV_TREE_2                pTree,
    PLWIO_SRV_FILE_2                pFile,
    PSRV_LOCK_REQUEST_STATE_SMB_V2* ppLockRequestState
    )
{
    NTSTATUS                       ntStatus          = STATUS_SUCCESS;
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState = NULL;

    ntStatus = SrvAllocateMemory(
                        sizeof(SRV_LOCK_REQUEST_STATE_SMB_V2),
                        (PVOID*)&pLockRequestState);
    BAIL_ON_NT_STATUS(ntStatus);

    pLockRequestState->stage = SRV_LOCK_STAGE_SMB_V2_INITIAL;

    pLockRequestState->ulTid          = pTree->ulTid;
    pLockRequestState->pFile          = SrvFile2Acquire(pFile);
    pLockRequestState->pRequestHeader = pLockRequestHeader;

    *ppLockRequestState = pLockRequestState;

cleanup:

    return ntStatus;

error:

    *ppLockRequestState = NULL;

    goto cleanup;
}

static
NTSTATUS
SrvProcessLockRequest_SMB_V2(
    PSRV_EXEC_CONTEXT              pExecContext,
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState
    )
{
    NTSTATUS ntStatus                       = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2     = pExecContext->pProtocolContext;
    PSMB2_LOCK_REQUEST_HEADER  pLockRequest = pLockRequestState->pRequestHeader;
    PSMB2_LOCK pLock                        = pLockRequest->locks;
    PSMB2_LOCK pLastLock                    = pLock + pLockRequest->usLockCount;
    BOOLEAN    bLocking                     = FALSE;

    if (pLock == pLastLock)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    bLocking = !LwIsSetFlag(pLock->ulFlags, SMB2_LOCK_FLAGS_UNLOCK);

    if (pLockRequestState->bLockPending)
    {
        ntStatus = pExecContext->ioStatusBlock.Status;
        BAIL_ON_NT_STATUS(ntStatus);

        pLock = &pLockRequest->locks[pLockRequestState->iLock];

        if (LwIsSetFlag(pLock->ulFlags, SMB2_LOCK_FLAGS_UNLOCK))
        {
            SrvFile2RegisterUnlock(pLockRequestState->pFile);
        }
        else
        {
            SrvFile2RegisterLock(pLockRequestState->pFile);
        }

        pLock++;
        pLockRequestState->iLock++;
        pLockRequestState->bLockPending = FALSE;
    }
    else if (bLocking && pCtxSmb2->ulNumRequests > 1 &&
             !LwIsSetFlag(pLock->ulFlags, SMB2_LOCK_FLAGS_FAIL_IMMEDIATELY) &&
             pCtxSmb2->iMsg != pCtxSmb2->ulNumRequests - 1)
    {
        /*
         * Force the client to send potentially long blocking
         * requests separately.
         */
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    for (; pLock < pLastLock; pLock++, pLockRequestState->iLock++)
    {
        ntStatus = SrvValidateLockRequest_SMB_V2(
                        pLock,
                        bLocking,
                        pLockRequest->usLockCount);
        BAIL_ON_NT_STATUS(ntStatus);

        SrvPrepareExecContextAsync(pExecContext);

        if (bLocking)
        {
            ntStatus = IoLockFile(
                            pLockRequestState->pFile->hFile,
                            pExecContext->pAcb,
                            &pExecContext->ioStatusBlock,
                            pLock->ullFileOffset,
                            pLock->ullByteRange,
                            pLockRequestState->pFile->bIsDurable ?
                                pLockRequest->ulLockSequence : 0,
                            LwIsSetFlag(pLock->ulFlags,
                                SMB2_LOCK_FLAGS_FAIL_IMMEDIATELY),
                            LwIsSetFlag(pLock->ulFlags,
                                SMB2_LOCK_FLAGS_EXCLUSIVE_LOCK));
        }
        else
        {
            ntStatus = IoUnlockFile(
                            pLockRequestState->pFile->hFile,
                            pExecContext->pAcb,
                            &pExecContext->ioStatusBlock,
                            pLock->ullFileOffset,
                            pLock->ullByteRange,
                            pLockRequestState->pFile->bIsDurable ?
                                pLockRequest->ulLockSequence : 0);
        }
        BAIL_ON_NT_STATUS(ntStatus);

        // Completed synchronously
        SrvReleaseExecContextAsync(pExecContext);
        SrvFile2RegisterUnlock(pLockRequestState->pFile);
    }

cleanup:

    return ntStatus;

error:

    if (ntStatus == STATUS_PENDING)
    {
        pLockRequestState->bLockPending = TRUE;
    }

    goto cleanup;
}

static
NTSTATUS
SrvValidateLockRequest_SMB_V2(
    PSMB2_LOCK pLock,
    BOOLEAN    bLocking,
    USHORT     usLockCount
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    ULONG ulLockBits = pLock->ulFlags;

    // Only one lock/unlock bit may be set.
    ulLockBits &= ~SMB2_LOCK_FLAGS_FAIL_IMMEDIATELY;
    if (ulLockBits == 0 || !LW_IS_POW2(ulLockBits))
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    // Cannot mix locking and unlocking (Logical XOR != 0).
    if (!bLocking == !LwIsSetFlag(pLock->ulFlags, SMB2_LOCK_FLAGS_UNLOCK))
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    // When requesting multiple locks, all must have the
    // fail immediately flag set.
    if (bLocking && usLockCount > 1 &&
        !LwIsSetFlag(pLock->ulFlags, SMB2_LOCK_FLAGS_FAIL_IMMEDIATELY))
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if ((pLock->ullFileOffset == UINT64_MAX) &&
        (pLock->ullByteRange == UINT64_MAX))
    {
        ntStatus = STATUS_INVALID_LOCK_RANGE;
        BAIL_ON_NT_STATUS(ntStatus);
    }

error:

    return ntStatus;
}

static
VOID
SrvClearLocks_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext,
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState
    )
{
    //
    // Unlock (backwards) locks that have already been acquired
    //
    while (pLockRequestState->iLock-- > 0)
    {
        NTSTATUS   ntStatus1 = STATUS_SUCCESS;
        PSMB2_LOCK pLock     =
            &pLockRequestState->pRequestHeader->locks[pLockRequestState->iLock];

        if (!LwIsSetFlag(pLock->ulFlags, SMB2_LOCK_FLAGS_UNLOCK))
        {
            ntStatus1 = IoUnlockFile(
                            pLockRequestState->pFile->hFile,
                            NULL,
                            &pExecContext->ioStatusBlock,
                            pLock->ullFileOffset,
                            pLock->ullByteRange,
                            pLockRequestState->pFile->bIsDurable ?
                                pLockRequestState->pRequestHeader->ulLockSequence :
                                0);
            if (ntStatus1)
            {
                LWIO_LOG_ERROR("Failed in unlock. error code [%d]", ntStatus1);
            }
            else
            {
                SrvFile2RegisterUnlock(pLockRequestState->pFile);
            }
        }
    }

    return;
}

static
NTSTATUS
SrvBuildLockResponse_SMB_V2(
    PSRV_EXEC_CONTEXT      pExecContext
    )
{
    NTSTATUS                   ntStatus      = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    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 ulBytesUsed      = 0;
    ULONG ulTotalBytesUsed = 0;

    ntStatus = SMB2MarshalHeader(
                pOutBuffer,
                ulOffset,
                ulBytesAvailable,
                COM2_LOCK,
                pSmbRequest->CreditCharge,
                pExecContext->usCreditsGranted,
                pSmbRequest->pHeader->ulPid,
                pSmbRequest->pHeader->ullCommandSequence,
                pCtxSmb2->pTree->ulTid,
                pCtxSmb2->pSession->ullUid,
                pExecContext->bInterimSent ? pExecContext->ullAsyncId : 0,
                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;

    ntStatus = SMB2MarshalLockResponse(
                    pOutBuffer,
                    ulOffset,
                    ulBytesAvailable,
                    &ulBytesUsed);
    BAIL_ON_NT_STATUS(ntStatus);

    // pOutBuffer += ulBytesUsed;
    // ulOffset += ulBytesUsed;
    // ulBytesAvailable -= ulBytesUsed;
    ulTotalBytesUsed += 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
SrvFreeLockRequestStateHandle_SMB_V2(
    HANDLE hLockRequestState
    )
{
    return SrvFreeLockRequestState_SMB_V2(hLockRequestState);
}

static
VOID
SrvFreeLockRequestState_SMB_V2(
    PSRV_LOCK_REQUEST_STATE_SMB_V2 pLockRequestState
    )
{
    if (pLockRequestState->pFile)
    {
        SrvFile2Release(pLockRequestState->pFile);
    }

    SrvFreeMemory(pLockRequestState);
}


