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

#include "includes.h"

static
NTSTATUS
SrvBuildIOCTLState_SMB_V2(
    PLWIO_SRV_CONNECTION       pConnection,
    PSMB2_IOCTL_REQUEST_HEADER pRequestHeader,
    PBYTE                      pData,
    PLWIO_SRV_FILE_2           pFile,
    PSRV_IOCTL_STATE_SMB_V2*   ppIOCTLState
    );

static
NTSTATUS
SrvExecuteIOCTL_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
NTSTATUS
SrvExecuteEnumerateSnapshots_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
NTSTATUS
SrvBuildIOCTLResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
VOID
SrvFreeIOCTLStateHandle_SMB_V2(
    HANDLE hIOCTLState
    );

static
VOID
SrvFreeIOCTLState_SMB_V2(
    PSRV_IOCTL_STATE_SMB_V2 pIOCTLState
    );

NTSTATUS
SrvProcessIOCTL_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_IOCTL_STATE_SMB_V2    pIOCTLState   = pCtxSmb2->hState;
    PLWIO_SRV_SESSION_2        pSession      = NULL;
    PLWIO_SRV_TREE_2           pTree         = NULL;
    PLWIO_SRV_FILE_2           pFile         = NULL;

    if (pIOCTLState == NULL)
    {
        ULONG                      iMsg           = pCtxSmb2->iMsg;
        PSRV_MESSAGE_SMB_V2        pSmbRequest    = &pCtxSmb2->pRequests[iMsg];
        PSMB2_IOCTL_REQUEST_HEADER pRequestHeader = NULL; // Do not free
        PBYTE                      pData          = 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 = SMB2UnmarshalIOCTLRequest(
                        pSmbRequest,
                        &pRequestHeader,
                        &pData);
        BAIL_ON_NT_STATUS(ntStatus);

        SRV_LOG_DEBUG(
            pExecContext->pLogContext,
            SMB_PROTOCOL_VERSION_2,
            pSmbRequest->pHeader->command,
            "IOCTL 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%llx,volatile:0x%llx),"
            "flags(0x%x),function-code(%u),"
            "input-length(%u),input-offset(%u),max-input-length(%u),"
            "output-length(%u),output-offset(%u),max-output-length(%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->ulFlags,
            pRequestHeader->ulFunctionCode,
            pRequestHeader->ulInLength,
            pRequestHeader->ulInOffset,
            pRequestHeader->ulMaxInLength,
            pRequestHeader->ulOutLength,
            pRequestHeader->ulOutOffset,
            pRequestHeader->ulMaxOutLength);

        switch (pRequestHeader->ulFunctionCode)
        {
            case IO_FSCTL_GET_DFS_REFERRALS:
            case IO_FSCTL_GET_DFS_REFERRALS_EX:
            
                ntStatus = STATUS_FS_DRIVER_REQUIRED;

                break;

            case IO_FSCTL_QUERY_NETWORK_INTERFACE_INFO:
            case IO_FSCTL_VALIDATE_NEGOTIATE_INFO: 
            case IO_FSCTL_PIPE_WAIT:

                ntStatus = STATUS_NOT_SUPPORTED;

                break;

            default:

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

                break;
        }
        BAIL_ON_NT_STATUS(ntStatus);

        ntStatus = SrvBuildIOCTLState_SMB_V2(
                        pConnection,
                        pRequestHeader,
                        pData,
                        pFile,
                        &pIOCTLState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb2->hState = pIOCTLState;
        pCtxSmb2->pfnStateRelease = &SrvFreeIOCTLStateHandle_SMB_V2;
    }

    switch (pIOCTLState->stage)
    {
        case SRV_IOCTL_STAGE_SMB_V2_INITIAL:

            pIOCTLState->stage = SRV_IOCTL_STAGE_SMB_V2_ATTEMPT_IO;

            // intentional fall through

        case SRV_IOCTL_STAGE_SMB_V2_ATTEMPT_IO:

            if ((pIOCTLState->pRequestHeader->ulFlags & 0x1) &&
                (pIOCTLState->pRequestHeader->ulFunctionCode ==
                    IO_FSCTL_SRV_ENUMERATE_SNAPSHOTS))
            {
                ntStatus = SrvExecuteEnumerateSnapshots_SMB_V2(pExecContext);
                BAIL_ON_NT_STATUS(ntStatus);
            }
            else
            {
                ntStatus = SrvExecuteIOCTL_SMB_V2(pExecContext);

                if (STATUS_BUFFER_OVERFLOW == ntStatus)
                {
                    ntStatus = STATUS_SUCCESS;
                }
                BAIL_ON_NT_STATUS(ntStatus);
            }

            pIOCTLState->stage = SRV_IOCTL_STAGE_SMB_V2_BUILD_RESPONSE;

            // intentional fall through

        case SRV_IOCTL_STAGE_SMB_V2_BUILD_RESPONSE:

            ntStatus = SrvBuildIOCTLResponse_SMB_V2(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pIOCTLState->stage = SRV_IOCTL_STAGE_SMB_V2_DONE;

            // intentional fall through

        case SRV_IOCTL_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
SrvBuildIOCTLState_SMB_V2(
    PLWIO_SRV_CONNECTION       pConnection,
    PSMB2_IOCTL_REQUEST_HEADER pRequestHeader,
    PBYTE                      pData,
    PLWIO_SRV_FILE_2           pFile,
    PSRV_IOCTL_STATE_SMB_V2*   ppIOCTLState
    )
{
    NTSTATUS                ntStatus    = STATUS_SUCCESS;
    PSRV_IOCTL_STATE_SMB_V2 pIOCTLState = NULL;

    ntStatus = SrvAllocateMemory(
                    sizeof(SRV_IOCTL_STATE_SMB_V2),
                    (PVOID*)&pIOCTLState);
    BAIL_ON_NT_STATUS(ntStatus);

    pIOCTLState->pConnection = SrvConnectionAcquire(pConnection);

    pIOCTLState->pFile = SrvFile2Acquire(pFile);

    pIOCTLState->pRequestHeader = pRequestHeader;
    pIOCTLState->pData          = pData;

    *ppIOCTLState = pIOCTLState;

cleanup:

    return ntStatus;

error:

    *ppIOCTLState = NULL;

    if (pIOCTLState)
    {
        SrvFreeIOCTLState_SMB_V2(pIOCTLState);
    }

    goto cleanup;
}

static
NTSTATUS
SrvExecuteIOCTL_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_IOCTL_STATE_SMB_V2    pIOCTLState   = pCtxSmb2->hState;

    if (pExecContext->pStatInfo)
    {
        ntStatus = SrvStatisticsSetIOCTL(
                        pExecContext->pStatInfo,
                        pIOCTLState->pRequestHeader->ulFunctionCode);
        BAIL_ON_NT_STATUS(ntStatus);
    }

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

    if (!pIOCTLState->pResponseBuffer)
    {
        // TODO: Should we just allocate 64 * 1024 bytes in this buffer?

        ntStatus = SMBPacketBufferAllocate(
                        pConnection->hPacketAllocator,
                        LW_MAX(1, pIOCTLState->pRequestHeader->ulMaxOutLength),
                        &pIOCTLState->pResponseBuffer,
                        &pIOCTLState->sResponseBufferLen);
        BAIL_ON_NT_STATUS(ntStatus);

        pIOCTLState->ulResponseBufferLen =
            pIOCTLState->pRequestHeader->ulMaxOutLength > 0 ?
            pIOCTLState->pRequestHeader->ulMaxOutLength:
            pIOCTLState->sResponseBufferLen;

        SrvPrepareExecContextAsync(pExecContext);

        if (pIOCTLState->pRequestHeader->ulFlags & 0x1)
        {
            ntStatus = IoFsControlFile(
                                    pIOCTLState->pFile->hFile,
                                    pExecContext->pAcb,
                                    &pExecContext->ioStatusBlock,
                                    pIOCTLState->pRequestHeader->ulFunctionCode,
                                    pIOCTLState->pData,
                                    pIOCTLState->pRequestHeader->ulInLength,
                                    pIOCTLState->pResponseBuffer,
                                    pIOCTLState->ulResponseBufferLen);
        }
        else
        {
            ntStatus = IoDeviceIoControlFile(
                                    pIOCTLState->pFile->hFile,
                                    pExecContext->pAcb,
                                    &pExecContext->ioStatusBlock,
                                    pIOCTLState->pRequestHeader->ulFunctionCode,
                                    pIOCTLState->pData,
                                    pIOCTLState->pRequestHeader->ulInLength,
                                    pIOCTLState->pResponseBuffer,
                                    pIOCTLState->ulResponseBufferLen);
        }
        BAIL_ON_NT_STATUS(ntStatus);

        SrvReleaseExecContextAsync(pExecContext); // completed sync
    }

    pIOCTLState->ulResponseBufferLen =
                                    pExecContext->ioStatusBlock.BytesTransferred;

cleanup:

    return ntStatus;

error:

    switch (ntStatus)
    {
        case STATUS_NOT_SUPPORTED:

            ntStatus = STATUS_INVALID_DEVICE_REQUEST;

            break;

        default:

            break;
    }

    goto cleanup;
}

static
NTSTATUS
SrvExecuteEnumerateSnapshots_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2 = pExecContext->pProtocolContext;
    PSRV_IOCTL_STATE_SMB_V2 pIOCTLState = pCtxSmb2->hState;
    ULONG outputBufferSize = 0;
    PBYTE pSnapshotArray = NULL;
    USHORT responseBufferLength = 0;

    // There should be no input buffer
    if (pIOCTLState->pRequestHeader->ulInLength != 0)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (pExecContext->pStatInfo)
    {
        ntStatus = SrvStatisticsSetIOCTL(
                        pExecContext->pStatInfo,
                        pIOCTLState->pRequestHeader->ulFunctionCode);
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (!pIOCTLState->pResponseBuffer)
    {
        if (pIOCTLState->pRequestHeader->ulMaxOutLength <
                sizeof(SMB_SRV_SNAPSHOT_ARRAY_HEADER))
        {
            ntStatus = STATUS_BUFFER_TOO_SMALL;
            BAIL_ON_NT_STATUS(ntStatus);
        }

        ntStatus = SrvShadowCopyCreateQueryBuffer(
                        pIOCTLState->pRequestHeader->ulMaxOutLength,
                        &responseBufferLength,
                        OUT_PPVOID(&pIOCTLState->pResponseBuffer));
        BAIL_ON_NT_STATUS(ntStatus);

        pIOCTLState->BypassedAllocator = TRUE;
        pIOCTLState->ulResponseBufferLen = responseBufferLength;

        SrvPrepareExecContextAsync(pExecContext);

        ntStatus = IoFsControlFile(
                                pIOCTLState->pFile->hFile,
                                pExecContext->pAcb,
                                &pExecContext->ioStatusBlock,
                                IO_FSCTL_QUERY_SNAPSHOTS,
                                NULL,
                                0,
                                pIOCTLState->pResponseBuffer,
                                pIOCTLState->ulResponseBufferLen);
        BAIL_ON_NT_STATUS(ntStatus);

        // Completed synchronously
        SrvReleaseExecContextAsync(pExecContext);
    }

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

    // Translate the response buffer that came back from the filesystem to a new
    // buffer to hand back to the client.  The new response buffer will be
    // filled with @GMT token strings instead of LONG64 time stamps.
    ntStatus = SrvShadowCopyCreateEnumerateResponse(
                    pIOCTLState->pRequestHeader->ulMaxOutLength,
                    (PIO_SNAPSHOT_LIST)pIOCTLState->pResponseBuffer,
                    &outputBufferSize,
                    OUT_PPVOID(&pSnapshotArray));
    BAIL_ON_NT_STATUS(ntStatus);

    // Free the response buffer that came from the filesystem and use the new
    // buffer instead.
    SRV_SAFE_FREE_MEMORY_AND_RESET(pIOCTLState->pResponseBuffer);
    pIOCTLState->pResponseBuffer = pSnapshotArray;
    pIOCTLState->BypassedAllocator = TRUE;
    pSnapshotArray = NULL;

    pIOCTLState->ulResponseBufferLen = outputBufferSize;
    pIOCTLState->sResponseBufferLen = outputBufferSize;
    pExecContext->ioStatusBlock.BytesTransferred = outputBufferSize;

error:
    LWIO_ASSERT(ntStatus != STATUS_BUFFER_OVERFLOW);

    if (ntStatus && (ntStatus != STATUS_PENDING))
    {
        SRV_SAFE_FREE_MEMORY_AND_RESET(pSnapshotArray);
        SRV_SAFE_FREE_MEMORY_AND_RESET(pIOCTLState->pResponseBuffer);
        pIOCTLState->BypassedAllocator = FALSE;
        pIOCTLState->ulResponseBufferLen = 0;
        pIOCTLState->sResponseBufferLen = 0;
        pExecContext->ioStatusBlock.BytesTransferred = 0;
    }

    return ntStatus;
}


static
NTSTATUS
SrvBuildIOCTLResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                   ntStatus      = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_IOCTL_STATE_SMB_V2    pIOCTLState   = pCtxSmb2->hState;
    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_IOCTL,
                    pSmbRequest->CreditCharge,
                    pExecContext->usCreditsGranted,
                    pSmbRequest->pHeader->ulPid,
                    pSmbRequest->pHeader->ullCommandSequence,
                    pCtxSmb2->pTree->ulTid,
                    pCtxSmb2->pSession->ullUid,
                    0LL, /* Async Id */
                    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;

    ntStatus = SMB2MarshalIOCTLResponse(
                    pOutBuffer,
                    ulOffset,
                    ulBytesAvailable,
                    pIOCTLState->pRequestHeader,
                    pIOCTLState->pResponseBuffer,
                    SMB_MIN(pIOCTLState->ulResponseBufferLen,
                            pIOCTLState->pRequestHeader->ulMaxOutLength),
                    &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
SrvFreeIOCTLStateHandle_SMB_V2(
    HANDLE hIOCTLState
    )
{
    return SrvFreeIOCTLState_SMB_V2(hIOCTLState);
}

static
VOID
SrvFreeIOCTLState_SMB_V2(
    PSRV_IOCTL_STATE_SMB_V2 pIOCTLState
    )
{
    if (pIOCTLState->pFile)
    {
        SrvFile2Release(pIOCTLState->pFile);
    }

    if (pIOCTLState->pResponseBuffer)
    {
        if (pIOCTLState->BypassedAllocator)
        {
            SRV_SAFE_FREE_MEMORY_AND_RESET(pIOCTLState->pResponseBuffer);
            pIOCTLState->BypassedAllocator = FALSE;
        }
        else
        {
            SMBPacketBufferFree(
                pIOCTLState->pConnection->hPacketAllocator,
                pIOCTLState->pResponseBuffer,
                pIOCTLState->sResponseBufferLen);
        }
    }

    if (pIOCTLState->pConnection)
    {
        SrvConnectionRelease(pIOCTLState->pConnection);
    }

    SrvFreeMemory(pIOCTLState);
}
