/* -*- 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:
 *
 *        notify_request.c
 *
 * Abstract:
 *
 *        Likewise IO (LWIO) - SRV
 *
 *        Protocols API - SMBV2
 *
 *        Change Notify Request
 *
 * Authors: Sriram Nambakam (snambakam@likewise.com)
 *
 */

#include "includes.h"

static
NTSTATUS
SrvBuildNotifyState_SMB_V2(
    PSMB2_NOTIFY_CHANGE_HEADER pRequestHeader,
    PLWIO_SRV_FILE_2           pFile,
    ULONG                      ulCompletionFilter,
    BOOLEAN                    bWatchTree,
    ULONG                      ulMaxBufferSize,
    PSRV_NOTIFY_STATE_SMB_V2*  ppNotifyState
    );

static
NTSTATUS
SrvExecuteChangeNotify_SMB_V2(
    PSRV_EXEC_CONTEXT        pExecContext,
    PSRV_NOTIFY_STATE_SMB_V2 pNotifyState
    );

static
NTSTATUS
SrvBuildNotifyResponse_SMB_V2(
    PSRV_EXEC_CONTEXT        pExecContext,
    PSRV_NOTIFY_STATE_SMB_V2 pNotifyState
    );

static
VOID
SrvFreeNotifyStateHandle_SMB_V2(
    HANDLE hNotifyState
    );

NTSTATUS
SrvProcessNotify_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];
    PLWIO_SRV_SESSION_2        pSession     = NULL;
    PLWIO_SRV_TREE_2           pTree        = NULL;
    PLWIO_SRV_FILE_2           pFile        = NULL;
    PSRV_NOTIFY_STATE_SMB_V2   pNotifyState = NULL;
    PLWIO_ASYNC_STATE          pAsyncState  = NULL;

    pNotifyState = pCtxSmb2->hState;
    if (pNotifyState == NULL)
    {
        PSMB2_NOTIFY_CHANGE_HEADER pRequestHeader = NULL; // Do not free

        if (pCtxSmb2->ulNumRequests > 1 &&
            pCtxSmb2->iMsg != pCtxSmb2->ulNumRequests - 1)
        {
            /*
             * Force the client to send potentially long blocking
             * requests separately.
             */
            ntStatus = STATUS_INSUFFICIENT_RESOURCES;
            BAIL_ON_NT_STATUS(ntStatus);
        }

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

        SRV_LOG_DEBUG(
                pExecContext->pLogContext,
                SMB_PROTOCOL_VERSION_2,
                pSmbRequest->pHeader->command,
                "Change notify 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),"
                "flags(0x%x),completion-filter(%u),output-buffer-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->usFlags,
                pRequestHeader->ulCompletionFilter,
                pRequestHeader->ulOutputBufferLength);

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

        if (pRequestHeader->ulOutputBufferLength > SMB_CN_MAX_BUFFER_SIZE)
        {
            ntStatus = STATUS_INVALID_PARAMETER;
            BAIL_ON_NT_STATUS(ntStatus);
        }

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

        pExecContext->ullAsyncId = pAsyncState->ullAsyncId;

        ntStatus = SrvBuildNotifyState_SMB_V2(
                        pRequestHeader,
                        pFile,
                        pRequestHeader->ulCompletionFilter,
                        pRequestHeader->usFlags & SMB2_NOTIFY_FLAGS_WATCH_TREE,
                        pRequestHeader->ulOutputBufferLength,
                        &pNotifyState);
        BAIL_ON_NT_STATUS(ntStatus);

        pCtxSmb2->hState = pNotifyState;
        pCtxSmb2->pfnStateRelease = &SrvFreeNotifyStateHandle_SMB_V2;

        pAsyncState->hAsyncState = SrvAcquireExecContext(pExecContext);
    }

    switch (pNotifyState->stage)
    {
        case SRV_NOTIFY_STAGE_SMB_V2_INITIAL:

            pNotifyState->stage = SRV_NOTIFY_STAGE_SMB_V2_ATTEMPT_IO;

            // intentional fall through

        case SRV_NOTIFY_STAGE_SMB_V2_ATTEMPT_IO:

            ntStatus = SrvExecuteChangeNotify_SMB_V2(
                            pExecContext,
                            pNotifyState);
            BAIL_ON_NT_STATUS(ntStatus);

            pNotifyState->stage = SRV_NOTIFY_STAGE_SMB_V2_BUILD_RESPONSE;

            // intentional fall through

        case SRV_NOTIFY_STAGE_SMB_V2_BUILD_RESPONSE:

            ntStatus = SrvBuildNotifyResponse_SMB_V2(
                            pExecContext,
                            pNotifyState);
            BAIL_ON_NT_STATUS(ntStatus);

            pNotifyState->stage = SRV_NOTIFY_STAGE_SMB_V2_DONE;

            // intentional fall through

        case SRV_NOTIFY_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:

    if (ntStatus == STATUS_PENDING)
    {
        NTSTATUS ntStatus2 = STATUS_SUCCESS;

        ntStatus2 = SrvInterimResponse_SMB_V2(pExecContext);
        if (ntStatus2 != STATUS_SUCCESS)
        {
            // TODO: Might have to cancel the entire operation
            //
            LWIO_LOG_ERROR(
                "Failed to build interim response [code:0x%8x]",
                ntStatus2);
        }
    }
    else
    {
        SrvReleaseExecContextAsync(pExecContext);
    }

    goto cleanup;
}

static
NTSTATUS
SrvBuildNotifyState_SMB_V2(
    PSMB2_NOTIFY_CHANGE_HEADER pRequestHeader,
    PLWIO_SRV_FILE_2           pFile,
    ULONG                      ulCompletionFilter,
    BOOLEAN                    bWatchTree,
    ULONG                      ulMaxBufferSize,
    PSRV_NOTIFY_STATE_SMB_V2*  ppNotifyState
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSRV_NOTIFY_STATE_SMB_V2 pNotifyState = NULL;

    ntStatus = SrvAllocateMemory(
                    sizeof(SRV_NOTIFY_STATE_SMB_V2),
                    (PVOID*)&pNotifyState);
    BAIL_ON_NT_STATUS(ntStatus);

    pNotifyState->stage              = SRV_NOTIFY_STAGE_SMB_V2_INITIAL;
    pNotifyState->pRequestHeader     = pRequestHeader;
    pNotifyState->pFile              = SrvFile2Acquire(pFile);
    pNotifyState->ulCompletionFilter = ulCompletionFilter;
    pNotifyState->bWatchTree         = bWatchTree;
    pNotifyState->ulMaxBufferSize    = ulMaxBufferSize;

    if (ulMaxBufferSize)
    {
        ntStatus = SrvAllocateMemory(
                        ulMaxBufferSize,
                        (PVOID*)&pNotifyState->pBuffer);
        BAIL_ON_NT_STATUS(ntStatus);
    }

    pNotifyState->ulBufferLength = ulMaxBufferSize;
    *ppNotifyState = pNotifyState;

cleanup:

    return ntStatus;

error:

    *ppNotifyState = NULL;

    if (pNotifyState)
    {
        SrvFreeNotifyStateHandle_SMB_V2(pNotifyState);
    }

    goto cleanup;
}

static
NTSTATUS
SrvExecuteChangeNotify_SMB_V2(
    PSRV_EXEC_CONTEXT        pExecContext,
    PSRV_NOTIFY_STATE_SMB_V2 pNotifyState
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;

    if (!pNotifyState->bStartedNotify)
    {
        SrvPrepareExecContextAsync(pExecContext);
        pNotifyState->bStartedNotify = TRUE;

        ntStatus = IoReadDirectoryChangeFile(
                        pNotifyState->pFile->hFile,
                        pExecContext->pAcb,
                        &pExecContext->ioStatusBlock,
                        pNotifyState->pBuffer,
                        pNotifyState->ulBufferLength,
                        pNotifyState->bWatchTree,
                        pNotifyState->ulCompletionFilter,
                        &pNotifyState->ulMaxBufferSize);

        if (ntStatus == STATUS_NOT_SUPPORTED)
        {
            //
            // The file system driver does not have support
            // to keep accumulating file change notifications
            //
            ntStatus = IoReadDirectoryChangeFile(
                            pNotifyState->pFile->hFile,
                            pExecContext->pAcb,
                            &pExecContext->ioStatusBlock,
                            pNotifyState->pBuffer,
                            pNotifyState->ulBufferLength,
                            pNotifyState->bWatchTree,
                            pNotifyState->ulCompletionFilter,
                            NULL);
        }
    }
    else
    {
        ntStatus = pExecContext->ioStatusBlock.Status;
    }
    BAIL_ON_NT_STATUS(ntStatus);

    pNotifyState->ulBytesUsed = pExecContext->ioStatusBlock.BytesTransferred;

cleanup:
    if (ntStatus != STATUS_PENDING)
    {
        SrvReleaseExecContextAsync(pExecContext);
        pNotifyState->bStartedNotify = FALSE;
    }

    return ntStatus;

error:
    if (ntStatus == STATUS_NOT_A_DIRECTORY)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
    }
    else if (ntStatus == STATUS_CANCELLED)
    {
        if (SrvFile2IsRundown(pNotifyState->pFile))
        {
            ntStatus = STATUS_NOTIFY_CLEANUP;
        }
    }

    goto cleanup;
}

static
NTSTATUS
SrvBuildNotifyResponse_SMB_V2(
    PSRV_EXEC_CONTEXT        pExecContext,
    PSRV_NOTIFY_STATE_SMB_V2 pNotifyState
    )
{
    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];
    PSMB2_NOTIFY_RESPONSE_HEADER pNotifyResponseHeader = NULL; // do not free
    PBYTE pOutBuffer       = pSmbResponse->pBuffer;
    ULONG ulBytesAvailable = pSmbResponse->ulBytesAvailable;
    ULONG ulDataOffset     = 0;
    ULONG ulOffset         = 0;
    ULONG ulBytesUsed      = 0;
    ULONG ulTotalBytesUsed = 0;

    ntStatus = SMB2MarshalHeader(
                pOutBuffer,
                ulOffset,
                ulBytesAvailable,
                COM2_NOTIFY,
                pSmbRequest->CreditCharge,
                pExecContext->usCreditsGranted,
                pSmbRequest->pHeader->ulPid,
                pSmbRequest->pHeader->ullCommandSequence,
                pCtxSmb2->pTree->ulTid,
                pCtxSmb2->pSession->ullUid,
                pExecContext->bInterimSent ? pExecContext->ullAsyncId : 0,
                pSmbRequest->pHeader->error,
                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 = SMB2MarshalNotifyResponse(
                    pOutBuffer,
                    ulOffset,
                    ulBytesAvailable,
                    pNotifyState->pBuffer,
                    pNotifyState->ulBytesUsed,
                    &ulDataOffset,
                    &pNotifyResponseHeader,
                    &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
SrvFreeNotifyStateHandle_SMB_V2(
    HANDLE hNotifyState
    )
{
    PSRV_NOTIFY_STATE_SMB_V2 pNotifyState = hNotifyState;

    if (pNotifyState->pFile)
    {
        SrvFile2Release(pNotifyState->pFile);
    }

    if (pNotifyState->pBuffer)
    {
        SrvFreeMemory(pNotifyState->pBuffer);
    }

    SrvFreeMemory(pNotifyState);
}
