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

#include "includes.h"

static
NTSTATUS
SrvExecuteQuerySecurityDescriptor_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    );

NTSTATUS
SrvGetSecurityInfo_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = NULL;

    pGetInfoState = (PSRV_GET_INFO_STATE_SMB_V2)pCtxSmb2->hState;

    switch (pGetInfoState->pRequestHeader->ucInfoClass)
    {
        case SMB2_SEC_INFO_CLASS_BASIC:

            if (pGetInfoState->pRequestHeader->ulOutputBufferLen >
                        SECURITY_DESCRIPTOR_RELATIVE_MAX_SIZE)
            {
                ntStatus = STATUS_INVALID_PARAMETER;
                BAIL_ON_NT_STATUS(ntStatus);
            }

            ntStatus = SrvExecuteQuerySecurityDescriptor_SMB_V2(pExecContext);

            break;

        default:

            ntStatus = STATUS_INVALID_INFO_CLASS;

            break;
    }

error:

    return ntStatus;
}

static
NTSTATUS
SrvExecuteQuerySecurityDescriptor_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = pCtxSmb2->hState;
    PSRV_PROCESS_INFO_STATE    pInfoState    = &pGetInfoState->infoState;
    BOOLEAN                    bContinue     = TRUE;
    PBYTE                      pErrorMessage = NULL;

    do
    {
        ntStatus = pExecContext->ioStatusBlock.Status;

        // The first time this function is called, the client issuing the
        // SMB2 SEC_INFO request may have specified a maximum
        // response size of zero (->pRequestHeader->ulOutputBufferLen).
        // In this case we need to return the current size of the SD. 
        // The client will then issue another call with a correctly sized 
        // "maximum response size".

        switch (ntStatus)
        {
            case STATUS_BUFFER_TOO_SMALL:
        
                if (pInfoState->ulOutputBufferLen == 0)
                {
                    // No output buffer implies a pure SD length query.

                    if (pInfoState->ulDataLen == 0)
                    {
                        // Since ulDataLen is zero and ntStatus
                        // is STATUS_BUFFER_TOO_SMALL, this is the initial
                        // execution of this function (not an asynchronous 
                        // callback). In this case we want to fall through
                        // and execute IoQuerySecurityFile() with a null 
                        // pData2 and a zero ulDataLength; this will, 
                        // effectively, force the lower layers to perform a 
                        // SD length query - returning the SD length in
                        // ulDataLength.
                        
                        LWIO_ASSERT(pInfoState->pData == NULL);
                        ntStatus = STATUS_SUCCESS;
                    }
                    else
                    {
                        // Asynchronous callback from our initial query
                        // preserve the STATUS_BUFFER_TOO_SMALL error and
                        // exit this loop
                        //
                        bContinue = FALSE;
                    }
                }
                else if (!pInfoState->pData)
                { 
                    // The caller has specified a maximum length, 
                    // but we don't yet know the size of the SD.  
                    // Rather than manufacture a null query as done above, 
                    // allocate the caller specified maximum.

                    ntStatus = SrvAllocateMemory(
                                    pInfoState->ulOutputBufferLen,
                                    OUT_PPVOID(&pInfoState->pData));
                    BAIL_ON_NT_STATUS(ntStatus);

                    pInfoState->ulDataLen = pInfoState->ulOutputBufferLen; 

                    LWIO_LOG_TRACE("allocated %d", pInfoState->ulDataLen);
                }
                else
                {
                    // The caller's maximum response size has been allocated
                    // yet the SD is still too big - log and return an error

                    LWIO_LOG_ERROR(
                        "ulOutputBufferLen %d too small, required length %d",
                        pInfoState->ulOutputBufferLen,
                        pInfoState->ulDataLen);
    
                    if (pInfoState->ulDataLen >=
                        SECURITY_DESCRIPTOR_RELATIVE_MAX_SIZE)
                    {
                            ntStatus = STATUS_INSUFFICIENT_RESOURCES;
                    }
                    // else preserve the STATUS_BUFFER_TOO_SMALL error
                }
                BAIL_ON_NT_STATUS(ntStatus);

                SrvPrepareExecContextAsync(pExecContext);

                ntStatus = IoQuerySecurityFile(
                                pInfoState->hFile,
                                pExecContext->pAcb,
                                &pExecContext->ioStatusBlock,
                                pGetInfoState->pRequestHeader->ulAdditionalInfo,
                                (PSECURITY_DESCRIPTOR_RELATIVE)pInfoState->pData,
                                &pInfoState->ulDataLen);
                switch (ntStatus)
                {
                    case STATUS_SUCCESS:
                    case STATUS_BUFFER_TOO_SMALL:

                        // completed synchronously
                        SrvReleaseExecContextAsync(pExecContext);

                        break;

                    default:

                        BAIL_ON_NT_STATUS(ntStatus);
                }

                break;

            case STATUS_SUCCESS:

                if (!pInfoState->pData)
                {
                    pExecContext->ioStatusBlock.Status = STATUS_BUFFER_TOO_SMALL;
                }
                else
                {
                    pInfoState->ulActualDataLen =
                        pExecContext->ioStatusBlock.BytesTransferred;

                    bContinue = FALSE;
                }

                break;

            default:

                BAIL_ON_NT_STATUS(ntStatus);

                break;
        }

    } while (bContinue);

cleanup:
    LWIO_LOG_TRACE(
        "status 0x%x, ulDataLength %d, ulOutputBufferLen %d "
        "pData2 %p, transfered %d",
        ntStatus,
        pInfoState->ulDataLen, 
        pInfoState->ulOutputBufferLen,
        pInfoState->pData,  
        pExecContext->ioStatusBlock.BytesTransferred);

    if (pErrorMessage)
    {
        SrvFreeMemory(pErrorMessage);
    }

    return ntStatus;

error:

    if (ntStatus == STATUS_BUFFER_TOO_SMALL)
    {
        NTSTATUS ntStatus2 = STATUS_SUCCESS;
        ULONG    ulLength  = 0;

        LWIO_LOG_TRACE(
            "Too small: ulDataLength %d, ulOutputBufferLen %d "
            "pData2 %p, transfered %d",
            pInfoState->ulDataLen,
            pInfoState->ulOutputBufferLen,
            pInfoState->pData,
            pExecContext->ioStatusBlock.BytesTransferred);

        LWIO_ASSERT(pInfoState->ulDataLen > 0);

        // Extract the current SD length and add a gratuitous
        // SECURITY_DESCRIPTOR_RELATIVE_MIN_SIZE bytes appropriately
        // limited by SECURITY_DESCRIPTOR_RELATIVE_MAX_SIZE.
            
        ulLength = LW_MIN(
            (pInfoState->ulDataLen +
             SECURITY_DESCRIPTOR_RELATIVE_MIN_SIZE),
            (SECURITY_DESCRIPTOR_RELATIVE_MAX_SIZE));

        ntStatus2 = SrvAllocateMemory(
                        sizeof(ULONG),
                        OUT_PPVOID(&pErrorMessage));
        if (ntStatus2)
        {
            LWIO_LOG_ERROR(
                "Failed to allocate buffer for error message (%s)\n",
                LwNtStatusToName(ntStatus2));
        }
        else
        {
            memcpy(pErrorMessage, (PBYTE)&ulLength, sizeof(ulLength));

            ntStatus2 = SrvSetErrorMessage_SMB_V2(
                            pCtxSmb2,
                            pErrorMessage,
                            sizeof(ulLength));
            if (ntStatus2 == STATUS_SUCCESS)
            {
                pErrorMessage = NULL;
            }
            else
            {
                LWIO_LOG_ERROR(
                   "Failed to set error message in exec context (%s)\n",
                    LwNtStatusToName(ntStatus2));
            }
        }
    }

    goto cleanup;
}

NTSTATUS
SrvBuildSecurityInfoResponse_SMB_V2(
    PSRV_EXEC_CONTEXT pExecContext
    )
{
    NTSTATUS                    ntStatus = STATUS_SUCCESS;
    PSRV_EXEC_CONTEXT_SMB_V2   pCtxSmb2      = pExecContext->pProtocolContext;
    PSRV_GET_INFO_STATE_SMB_V2 pGetInfoState = pCtxSmb2->hState;
    PSRV_PROCESS_INFO_STATE    pInfoState    = &pGetInfoState->infoState;
    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 ulTotalBytesUsed = 0;
    PSMB2_GET_INFO_RESPONSE_HEADER pGetInfoResponseHeader = NULL;

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

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

    pGetInfoResponseHeader = (PSMB2_GET_INFO_RESPONSE_HEADER)pOutBuffer;

    ulBytesAvailable -= sizeof(SMB2_GET_INFO_RESPONSE_HEADER);
    pOutBuffer       += sizeof(SMB2_GET_INFO_RESPONSE_HEADER);
    ulOffset         += sizeof(SMB2_GET_INFO_RESPONSE_HEADER);
    ulTotalBytesUsed += sizeof(SMB2_GET_INFO_RESPONSE_HEADER);

    pGetInfoResponseHeader->usLength = sizeof(SMB2_GET_INFO_RESPONSE_HEADER)+1;
    pGetInfoResponseHeader->usOutBufferOffset = ulOffset;

    if (ulBytesAvailable < pInfoState->ulActualDataLen)
    {
        ntStatus = STATUS_INVALID_BUFFER_SIZE;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (pInfoState->ulActualDataLen)
    {
        memcpy(pOutBuffer,
               pInfoState->pData,
               pInfoState->ulActualDataLen);
    }

    pGetInfoResponseHeader->ulOutBufferLength = pInfoState->ulActualDataLen;

    // pOutBuffer       += pGetInfoState->ulDataLength;
    // ulBytesAvailable -= pGetInfoState->ulDataLength;
    // ulOffset         += pGetInfoState->ulDataLength;

    ulTotalBytesUsed += pGetInfoResponseHeader->ulOutBufferLength;

    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;
}

