/* -*- 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
SrvBuildNtRenameState(
    PSMB_NT_RENAME_REQUEST_HEADER pRequestHeader,
    PWSTR                         pwszOldName,
    PWSTR                         pwszNewName,
    LONG64                        OldSnapshotTime,
    PSRV_NT_RENAME_STATE_SMB_V1*  ppRenameState
    );

static
VOID
SrvLogNtRename_SMB_V1(
    PSRV_LOG_CONTEXT pLogContext,
    LWIO_LOG_LEVEL   logLevel,
    PCSTR            pszFunction,
    PCSTR            pszFile,
    ULONG            ulLine,
    ...
    );

static
NTSTATUS
SrvExecuteNtRename(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
NTSTATUS
SrvBuildNtRenameResponse(
    PSRV_EXEC_CONTEXT pExecContext
    );

static
VOID
SrvFreeNtRenameStateHandle(
    HANDLE hState
    );

static
VOID
SrvFreeNtRenameState(
    PSRV_NT_RENAME_STATE_SMB_V1 pRenameState
    );

static
NTSTATUS
SrvValidateStreamNewName(
    PWSTR pwszOldName,
    PWSTR pwszNewName
    );

NTSTATUS
SrvProcessNtRename(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                    ntStatus     = 0;
    PLWIO_SRV_CONNECTION        pConnection  = pExecContext->pConnection;
    PSRV_EXEC_CONTEXT_SMB_V1    pCtxSmb1     = pExecContext->pProtocolContext;
    PSRV_NT_RENAME_STATE_SMB_V1 pRenameState = pCtxSmb1->hState;
    PLWIO_SRV_SESSION           pSession     = NULL;
    PLWIO_SRV_TREE              pTree        = NULL;
    BOOLEAN                     processSnapshots = FALSE;
    LONG64                      oldSnapshotTime = 0;

    if (pRenameState)
    {
        ntStatus = SRV_SCHEDULE_IF(
                        pExecContext,
                        pRenameState->hFile || pRenameState->hDir);
        BAIL_ON_NT_STATUS(ntStatus);
    }
    else
    {
        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;
        PSMB_NT_RENAME_REQUEST_HEADER pRequestHeader = NULL; // Do not free
        PWSTR                      pwszOldName    = NULL; // Do not free
        PWSTR                      pwszNewName    = 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);

        processSnapshots = SrvShouldProcessSnapshots(
                                pSmbRequest->pHeader,
                                pCtxSmb1->pTree->UnderstandSnapshots);
        ntStatus = WireUnmarshallNtRenameRequest(
                        pBuffer,
                        ulBytesAvailable,
                        ulOffset,
                        &pRequestHeader,
                        &pwszOldName,
                        &pwszNewName,
                        processSnapshots ? &oldSnapshotTime : NULL);
        BAIL_ON_NT_STATUS(ntStatus);

        SRV_LOG_CALL_DEBUG(
                pExecContext->pLogContext,
                SMB_PROTOCOL_VERSION_1,
                pSmbRequest->pHeader->command,
                &SrvLogNtRename_SMB_V1,
                pRequestHeader,
                pwszOldName,
                pwszNewName);

        ntStatus = SrvBuildNtRenameState(
                        pRequestHeader,
                        pwszOldName,
                        pwszNewName,
                        oldSnapshotTime,
                        &pRenameState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb1->hState = pRenameState;
        pCtxSmb1->pfnStateRelease = &SrvFreeNtRenameStateHandle;
    }

    switch (pRenameState->stage)
    {
        case SRV_NT_RENAME_STAGE_SMB_V1_INITIAL:

            ntStatus = STATUS_SUCCESS;
            switch(pRenameState->pRequestHeader->usInfoLevel)
            {
                case SMB_NT_RENAME_SET_LINK_INFO:
                case SMB_NT_RENAME_RENAME_FILE:
                    // supported info level
                    break;

                case SMB_NT_RENAME_MOVE_FILE:
                    // unsupported info level
                    ntStatus = STATUS_NOT_SUPPORTED;
                    break;

                default:
                    ntStatus = STATUS_INVALID_INFO_CLASS;
                    break;
            }
            BAIL_ON_NT_STATUS(ntStatus);

            ntStatus = SrvBuildTreeRelativePath(
                            pCtxSmb1->pTree,
                            pRenameState->pwszOldName,
                            &pRenameState->oldName);
            BAIL_ON_NT_STATUS(ntStatus);

            ntStatus = SrvBuildTreeRelativePath(
                            pCtxSmb1->pTree,
                            NULL,
                            &pRenameState->dirPath);
            BAIL_ON_NT_STATUS(ntStatus);

            ntStatus = SrvInitializeUnicodeString(
                            pRenameState->pwszNewName,
                            &pRenameState->newName.Name);
            BAIL_ON_NT_STATUS(ntStatus);

            pRenameState->newName.RootFileHandle = pTree->hFile;

            pRenameState->stage = SRV_NT_RENAME_STAGE_SMB_V1_ATTEMPT_RENAME;

            // intentional fall through

        case SRV_NT_RENAME_STAGE_SMB_V1_ATTEMPT_RENAME:

            ntStatus = SrvExecuteNtRename(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pRenameState->stage = SRV_NT_RENAME_STAGE_SMB_V1_BUILD_RESPONSE;

            // intentional fall through

        case SRV_NT_RENAME_STAGE_SMB_V1_BUILD_RESPONSE:

            ntStatus = SrvBuildNtRenameResponse(pExecContext);
            BAIL_ON_NT_STATUS(ntStatus);

            pRenameState->stage = SRV_NT_RENAME_STAGE_SMB_V1_DONE;

            // intentional fall through

        case SRV_NT_RENAME_STAGE_SMB_V1_DONE:

            break;
    }

cleanup:

    if (pSession)
    {
        SrvSessionRelease(pSession);
    }

    if (pTree)
    {
        SrvTreeRelease(pTree);
    }

    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
SrvValidateStreamNewName(
    PWSTR pwszOldName,
    PWSTR pwszNewName
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    wchar16_t wszColon[] = {':', 0};

    while(!IsNullOrEmptyString(pwszOldName))
    {
        if (*pwszOldName++ == wszColon[0])
        {
            if (*pwszNewName != wszColon[0] ||
                IsNullOrEmptyString((pwszNewName+1)))
            {
                ntStatus = STATUS_INVALID_PARAMETER;
                BAIL_ON_NT_STATUS(ntStatus);
            }

            break;
        }
    }

error:

    return ntStatus;
}

static
NTSTATUS
SrvBuildNtRenameState(
    PSMB_NT_RENAME_REQUEST_HEADER pRequestHeader,
    PWSTR                         pwszOldName,
    PWSTR                         pwszNewName,
    LONG64                        OldSnapshotTime,
    PSRV_NT_RENAME_STATE_SMB_V1*  ppRenameState
    )
{
    NTSTATUS                    ntStatus     = STATUS_SUCCESS;
    PSRV_NT_RENAME_STATE_SMB_V1 pRenameState = NULL;

    if (!pwszOldName || !*pwszOldName || !pwszNewName || !*pwszNewName)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    ntStatus = SrvValidateStreamNewName(pwszOldName, pwszNewName);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus = SrvAllocateMemory(
                    sizeof(SRV_NT_RENAME_STATE_SMB_V1),
                    (PVOID*)&pRenameState);
    BAIL_ON_NT_STATUS(ntStatus);

    pRenameState->stage = SRV_NT_RENAME_STAGE_SMB_V1_INITIAL;

    pRenameState->pRequestHeader = pRequestHeader;
    pRenameState->pwszOldName    = pwszOldName;
    pRenameState->pwszNewName    = pwszNewName;
    pRenameState->oldSnapshotTime = OldSnapshotTime;

    *ppRenameState = pRenameState;

cleanup:

    return ntStatus;

error:

    *ppRenameState = NULL;

    if (pRenameState)
    {
        SrvFreeNtRenameState(pRenameState);
    }

    goto cleanup;
}

static
VOID
SrvLogNtRename_SMB_V1(
    PSRV_LOG_CONTEXT pLogContext,
    LWIO_LOG_LEVEL   logLevel,
    PCSTR            pszFunction,
    PCSTR            pszFile,
    ULONG            ulLine,
    ...
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSMB_NT_RENAME_REQUEST_HEADER pRequestHeader = NULL;
    PWSTR pwszOldName = NULL;
    PWSTR pwszNewName = NULL;
    PSTR  pszOldName  = NULL;
    PSTR  pszNewName  = NULL;
    va_list msgList;

    va_start(msgList, ulLine);
    pRequestHeader = va_arg(msgList, PSMB_NT_RENAME_REQUEST_HEADER);
    pwszOldName    = va_arg(msgList, PWSTR);
    pwszNewName    = va_arg(msgList, PWSTR);

    if (pwszOldName)
    {
        ntStatus = SrvWc16sToMbs(pwszOldName, &pszOldName);
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (pwszNewName)
    {
        ntStatus = SrvWc16sToMbs(pwszNewName, &pszNewName);
        BAIL_ON_NT_STATUS(ntStatus);
    }

    LW_RTL_LOG_RAW(
        logLevel,
        "srv",
        pszFunction,
        pszFile,
        ulLine,
        "NtRename Parameters: cluster-count(%u),info-level(%u),search-attrs(0x%x),old-name(%s),new-name(%s)",
        pRequestHeader->ulClusterCount,
        pRequestHeader->usInfoLevel,
        pRequestHeader->usSearchAttributes,
        LWIO_SAFE_LOG_STRING(pszOldName),
        LWIO_SAFE_LOG_STRING(pszNewName));

error:

    va_end(msgList);

    SRV_SAFE_FREE_MEMORY(pszOldName);
    SRV_SAFE_FREE_MEMORY(pszNewName);

    return;
}

static
NTSTATUS
SrvExecuteNtRename(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                    ntStatus     = 0;
    PSRV_EXEC_CONTEXT_SMB_V1    pCtxSmb1     = pExecContext->pProtocolContext;
    PSRV_NT_RENAME_STATE_SMB_V1 pRenameState = pCtxSmb1->hState;

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

    if (!pRenameState->hDir)
    {
        SrvPrepareExecContextAsync(pExecContext);

        ntStatus = SrvIoCreateFile(
                        pExecContext,
                        pCtxSmb1->pTree->pShareInfo,
                        &pRenameState->hDir,
                        pExecContext->pAcb,
                        &pExecContext->ioStatusBlock,
                        pCtxSmb1->pSession->pIoSecurityContext,
                        &pRenameState->dirPath,
                        pRenameState->pSecurityDescriptor,
                        pRenameState->pSecurityQOS,
                        GENERIC_READ,
                        0,
                        0,
                        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                        FILE_OPEN,
                        FILE_DIRECTORY_FILE,
                        NULL, /* EA Buffer */
                        0,    /* EA Length */
                        0, // no snapshot since this is share root
                        &pRenameState->pDirEcpList
                        );
        BAIL_ON_NT_STATUS(ntStatus);

        SrvReleaseExecContextAsync(pExecContext); // completed synchronously
    }

    if (!pRenameState->hFile)
    {
        SrvPrepareExecContextAsync(pExecContext);

        ntStatus = SrvIoCreateFile(
                        pExecContext,
                        pCtxSmb1->pTree->pShareInfo,
                        &pRenameState->hFile,
                        pExecContext->pAcb,
                        &pExecContext->ioStatusBlock,
                        pCtxSmb1->pSession->pIoSecurityContext,
                        &pRenameState->oldName,
                        pRenameState->pSecurityDescriptor,
                        pRenameState->pSecurityQOS,
                        DELETE,
                        0,
                        FILE_ATTRIBUTE_NORMAL,
                        FILE_SHARE_READ,
                        FILE_OPEN,
                        0,
                        NULL, /* EA Buffer */
                        0,    /* EA Length */
                        &pRenameState->oldSnapshotTime,
                        &pRenameState->pFileEcpList
                        );
        BAIL_ON_NT_STATUS(ntStatus);

        SrvReleaseExecContextAsync(pExecContext); // completed synchronously
    }

    switch(pRenameState->pRequestHeader->usInfoLevel)
    {
        case SMB_NT_RENAME_RENAME_FILE:
            if (!pRenameState->Info.pFileRenameInfo)
            {
                pRenameState->ulDataLen =
                    LW_FIELD_OFFSET(FILE_RENAME_INFORMATION, FileName) +
                    pRenameState->newName.Name.Length;

                ntStatus = SrvAllocateMemory(
                               pRenameState->ulDataLen,
                               (PVOID*)&pRenameState->pData);
                BAIL_ON_NT_STATUS(ntStatus);

                pRenameState->Info.pFileRenameInfo =
                    (PFILE_RENAME_INFORMATION)pRenameState->pData;

                pRenameState->Info.pFileRenameInfo->ReplaceIfExists = FALSE;
                pRenameState->Info.pFileRenameInfo->RootDirectory   = pRenameState->hDir;
                pRenameState->Info.pFileRenameInfo->FileNameLength  =
                    pRenameState->newName.Name.Length;
                memcpy(
                    pRenameState->Info.pFileRenameInfo->FileName,
                    pRenameState->newName.Name.Buffer,
                    pRenameState->Info.pFileRenameInfo->FileNameLength);

                SrvPrepareExecContextAsync(pExecContext);

                ntStatus = IoSetInformationFile(
                               pRenameState->hFile,
                               pExecContext->pAcb,
                               &pExecContext->ioStatusBlock,
                               pRenameState->Info.pFileRenameInfo,
                               pRenameState->ulDataLen,
                               FileRenameInformation);
                BAIL_ON_NT_STATUS(ntStatus);

                SrvReleaseExecContextAsync(pExecContext); // completed synchronously
            }
            break;

        case SMB_NT_RENAME_SET_LINK_INFO:
            if (!pRenameState->Info.pFileLinkInfo)
            {
                pRenameState->ulDataLen =
                    LW_FIELD_OFFSET(FILE_LINK_INFORMATION, FileName) +
                    pRenameState->newName.Name.Length;

                ntStatus = SrvAllocateMemory(
                               pRenameState->ulDataLen,
                               (PVOID*)&pRenameState->pData);
                BAIL_ON_NT_STATUS(ntStatus);

                pRenameState->Info.pFileLinkInfo =
                    (PFILE_LINK_INFORMATION)pRenameState->pData;

                pRenameState->Info.pFileLinkInfo->ReplaceIfExists = FALSE;
                pRenameState->Info.pFileLinkInfo->RootDirectory   = pRenameState->hDir;
                pRenameState->Info.pFileLinkInfo->FileNameLength  =
                    pRenameState->newName.Name.Length;
                memcpy(
                    pRenameState->Info.pFileLinkInfo->FileName,
                    pRenameState->newName.Name.Buffer,
                    pRenameState->Info.pFileLinkInfo->FileNameLength);

                SrvPrepareExecContextAsync(pExecContext);

                ntStatus = IoSetInformationFile(
                               pRenameState->hFile,
                               pExecContext->pAcb,
                               &pExecContext->ioStatusBlock,
                               pRenameState->Info.pFileLinkInfo,
                               pRenameState->ulDataLen,
                               FileLinkInformation);
                BAIL_ON_NT_STATUS(ntStatus);

                SrvReleaseExecContextAsync(pExecContext); // completed synchronously
            }
            break;

        default:
            // Valid infor levels were already checked in the caller
            ntStatus = STATUS_INVALID_PARAMETER;
            break;
    }
    BAIL_ON_NT_STATUS(ntStatus);


error:

    return ntStatus;
}

static
NTSTATUS
SrvBuildNtRenameResponse(
    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];
    PSMB_NT_RENAME_RESPONSE_HEADER pResponseHeader = NULL; // Do not free
    PBYTE pOutBuffer           = pSmbResponse->pBuffer;
    ULONG ulBytesAvailable     = pSmbResponse->ulBytesAvailable;
    ULONG ulOffset             = 0;
    USHORT usBytesUsed          = 0;
    ULONG ulTotalBytesUsed     = 0;

    if (!pSmbResponse->ulSerialNum)
    {
        ntStatus = SrvMarshalHeader_SMB_V1(
                        pOutBuffer,
                        ulOffset,
                        ulBytesAvailable,
                        COM_NT_RENAME,
                        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_NT_RENAME,
                        &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;

    ntStatus = WireMarshallNtRenameResponse(
                    pOutBuffer,
                    ulBytesAvailable,
                    ulOffset,
                    &pResponseHeader,
                    &usBytesUsed);
    BAIL_ON_NT_STATUS(ntStatus);

    // pOutBuffer       += usBytesUsed;
    // ulOffset         += usBytesUsed;
    // ulBytesAvailable -= usBytesUsed;
    ulTotalBytesUsed += usBytesUsed;

    pResponseHeader->usByteCount = 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;
}

static
VOID
SrvFreeNtRenameStateHandle(
    HANDLE hState
    )
{
    SrvFreeNtRenameState(hState);
}

static
VOID
SrvFreeNtRenameState(
    PSRV_NT_RENAME_STATE_SMB_V1 pRenameState
    )
{
    if (pRenameState->pDirEcpList)
    {
        IoRtlEcpListFree(&pRenameState->pDirEcpList);
    }

    if (pRenameState->pFileEcpList)
    {
        IoRtlEcpListFree(&pRenameState->pFileEcpList);
    }

    // TODO: Free the following if set
    // pSecurityDescriptor;
    // pSecurityQOS;

    SRV_FREE_UNICODE_STRING(&pRenameState->oldName.Name);

    SRV_FREE_UNICODE_STRING(&pRenameState->dirPath.Name);

    if (pRenameState->hDir)
    {
        IoCloseFile(pRenameState->hDir);
    }

    if (pRenameState->hFile)
    {
        IoCloseFile(pRenameState->hFile);
    }

    if (pRenameState->pData)
    {
        SrvFreeMemory(pRenameState->pData);
    }

    SrvFreeMemory(pRenameState);
}
