/* Editor Settings: expandtabs and use 4 spaces for indentation
 * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
 */

/*
 * Copyright Likewise Software    2004-2009
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the license, or (at
 * your option) any later version.
 *
 * This library 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 Lesser
 * General Public License for more details.  You should have received a copy
 * of the GNU Lesser 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
 * LESSER 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:
 *
 *        samr_querydisplayinfo.c
 *
 * Abstract:
 *
 *        Remote Procedure Call (RPC) Server Interface
 *
 *        SamrQueryDisplayInfo function
 *
 * Authors: Rafal Szczesniak (rafal@likewise.com)
 */

#include "includes.h"


static
NTSTATUS
SamrSrvFillDisplayInfoFull(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfo *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    );


static
NTSTATUS
SamrSrvFillDisplayInfoGeneral(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfo *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    );


static
NTSTATUS
SamrSrvFillDisplayInfoGeneralGroups(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfo *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    );


static
NTSTATUS
SamrSrvFillDisplayInfoAscii(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfoAscii *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    );


NTSTATUS
SamrSrvQueryDisplayInfo(
    IN  handle_t IDL_handle,
    IN  DOMAIN_HANDLE hDomain,
    IN  UINT16 level,
    IN  UINT32 start_idx,
    IN  UINT32 max_entries,
    IN  UINT32 buf_size,
    OUT UINT32 *total_size,
    OUT UINT32 *returned_size,
    OUT SamrDisplayInfo *info
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    NTSTATUS ntEnumStatus = STATUS_SUCCESS;
    DWORD dwError = 0;
    PDOMAIN_CONTEXT pDomCtx = NULL;
    SAMDB_OBJECT_TYPE ObjectType = 0;
    SAMDB_ENUM_HANDLE EnumHandle = {0};
    PSAMDB_OBJECT_INFO *ppObjects = NULL;
    PSAMDB_OBJECT_INFO pObject = NULL;
    DWORD dwObjectsNum = 0;
    SamrDisplayInfo Info;
    DWORD dwTotalSize = 0;
    DWORD dwSize = 0;
    DWORD dwCount = 0;
    DWORD i = 0;

    memset(&Info, 0, sizeof(Info));

    pDomCtx = (PDOMAIN_CONTEXT)hDomain;

    if (pDomCtx == NULL || pDomCtx->Type != SamrContextDomain)
    {
        ntStatus = STATUS_INVALID_HANDLE;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (!(pDomCtx->dwAccessGranted & DOMAIN_ACCESS_OPEN_ACCOUNT))
    {
        ntStatus = STATUS_ACCESS_DENIED;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    switch (level) {
    case 1:
    case 2:
    case 4:
    case 5:
        ObjectType = SAMDB_OBJECT_TYPE_USER;
        break;

    case 3:
        ObjectType = SAMDB_OBJECT_TYPE_LOCAL_GROUP;
        break;

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

    dwError = SamDbOpenEnumObjects(
                      pDomCtx->pDomainSid,
                      ObjectType,
                      SAMDB_ENUM_SORT_ORDER_ASCENDING,
                      &EnumHandle);
    BAIL_ON_LSA_ERROR(dwError);

    if (start_idx > 0)
    {
        DWORD skipCount = start_idx + 1;

        dwError = SamDbEnumObjects(
                          EnumHandle,
                          skipCount,
                          &dwObjectsNum,
                          &ppObjects);
        BAIL_ON_LSA_ERROR(dwError);

        if (ppObjects)
        {
            SamDbFreeObjects(dwObjectsNum, ppObjects);
            ppObjects = NULL;
            dwObjectsNum = 0;
        }
    }

    dwError = SamDbEnumObjects(
                      EnumHandle,
                      max_entries,
                      &dwObjectsNum,
                      &ppObjects);
    if (dwError == ERROR_NO_MORE_ITEMS)
    {
        ntEnumStatus = STATUS_NO_MORE_ENTRIES;
        dwError = ERROR_SUCCESS;
    }
    else if (dwError == ERROR_MORE_DATA)
    {
        // SamrQueryDisplayInfo function does not report STATUS_MORE_ENTRIES
        dwError = ERROR_SUCCESS;
    }
    else if (dwError != ERROR_SUCCESS)
    {
        BAIL_ON_LSA_ERROR(dwError);
    }

    dwTotalSize += sizeof(UINT32);    /* "count" field in info structure */

    for (i = 0; i < dwObjectsNum; i++)
    {
        pObject = ppObjects[i];

        switch (level) {
        case 1:
            ntStatus = SamrSrvFillDisplayInfoFull(pDomCtx,
                                                  pObject,
                                                  NULL,
                                                  i,
                                                  dwCount,
                                                  &dwTotalSize);
            break;

        case 2:
            ntStatus = SamrSrvFillDisplayInfoGeneral(pDomCtx,
                                                     pObject,
                                                     NULL,
                                                     i,
                                                     dwCount,
                                                     &dwTotalSize);
            break;

        case 3:
            ntStatus = SamrSrvFillDisplayInfoGeneralGroups(pDomCtx,
                                                           pObject,
                                                           NULL,
                                                           i,
                                                           dwCount,
                                                           &dwTotalSize);
            break;

        case 4:
        case 5:
            ntStatus = SamrSrvFillDisplayInfoAscii(pDomCtx,
                                                   pObject,
                                                   NULL,
                                                   i,
                                                   dwCount,
                                                   &dwTotalSize);
            break;
        }

        BAIL_ON_NT_STATUS(ntStatus);

        if (dwTotalSize < buf_size && i < max_entries) {
            dwCount = i + 1;
        }
    }

    /* At least one account entry is returned regardless of declared
       max response size */
    dwCount  = (!dwCount) ? 1 : dwCount;

    dwSize += sizeof(UINT32);    /* "count" field in info structure */

    if (dwObjectsNum == 0)
    {
        i = 0;
        ntStatus = STATUS_NO_MORE_ENTRIES;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    for (i = 0; i < dwCount && i < dwObjectsNum; i++)
    {
        pObject = ppObjects[i];

        switch (level)
        {
        case 1:
            ntStatus = SamrSrvFillDisplayInfoFull(pDomCtx,
                                                  pObject,
                                                  &Info,
                                                  i,
                                                  dwCount,
                                                  &dwSize);
            break;

        case 2:
            ntStatus = SamrSrvFillDisplayInfoGeneral(pDomCtx,
                                                     pObject,
                                                     &Info,
                                                     i,
                                                     dwCount,
                                                     &dwSize);
            break;

        case 3:
            ntStatus = SamrSrvFillDisplayInfoGeneralGroups(pDomCtx,
                                                           pObject,
                                                           &Info,
                                                           i,
                                                           dwCount,
                                                           &dwSize);
            break;

        case 4:
            ntStatus = SamrSrvFillDisplayInfoAscii(pDomCtx,
                                                   pObject,
                                                   &Info.info4,
                                                   i,
                                                   dwCount,
                                                   &dwSize);
            break;

        case 5:
            ntStatus = SamrSrvFillDisplayInfoAscii(pDomCtx,
                                                   pObject,
                                                   &Info.info5,
                                                   i,
                                                   dwCount,
                                                   &dwSize);
            break;
        }

        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (dwCount < dwObjectsNum)
    {
        ntStatus = STATUS_MORE_ENTRIES;
    }

    *total_size    = dwTotalSize;
    *returned_size = dwSize;
    *info          = Info;

cleanup:
    if (EnumHandle)
    {
        SamDbCloseEnum(EnumHandle);
    }

    if (ppObjects)
    {
        SamDbFreeObjects(dwObjectsNum, ppObjects);
    }

    if (ntStatus == STATUS_SUCCESS &&
        dwError != ERROR_SUCCESS)
    {
        ntStatus = LwWin32ErrorToNtStatus(dwError);
    }

    if (ntStatus == STATUS_SUCCESS &&
        ntEnumStatus != STATUS_SUCCESS)
    {
        ntStatus = ntEnumStatus;
    }

    return ntStatus;

error:
    /* Regardless of info level the pointer is at the same position */
    memset(&Info, 0, sizeof(Info));

    *total_size    = dwTotalSize;
    *returned_size = 0;
    *info          = Info;

    goto cleanup;
}


static
NTSTATUS
SamrSrvFillDisplayInfoFull(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfo *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSID pSid = NULL;
    DWORD dwRid = 0;
    SamrDisplayInfoFull *pInfo1 = NULL;
    SamrDisplayEntryFull *pDisplayEntry = NULL;
    DWORD dwSize = 0;

    if (pObject->Type != SAMDB_OBJECT_TYPE_USER)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS (ntStatus);
    }

    dwSize  = (*pdwSize);
    dwSize += sizeof(pInfo->info1.entries[0]);
    dwSize += wc16slen(pObject->Name) * sizeof(WCHAR);

    if (pObject->Info.User.FullName)
    {
        dwSize += wc16slen(pObject->Info.User.FullName) * sizeof(WCHAR);
    }

    if (pObject->Info.User.Description)
    {
        dwSize += wc16slen(pObject->Info.User.Description) * sizeof(WCHAR);
    }

    /* If NULL pointer is passed we're just calculating the size */
    if (pInfo == NULL) goto done;
    pInfo1 = &pInfo->info1;

    if (!pInfo1->entries) {
        ntStatus = SamrSrvAllocateMemory(
                            (void**)&pInfo1->entries,
                            sizeof(pInfo1->entries[0]) * dwCount);
        pInfo1->count = dwCount;
    }

    pDisplayEntry = &(pInfo1->entries[i]);

    //pDisplayEntry->idx           = (UINT32)llRecId;
    // KKJA: for now, this is i.
    pDisplayEntry->idx = i;

    pSid = pObject->Sid;

    dwRid = pSid->SubAuthority[pSid->SubAuthorityCount - 1];

    pDisplayEntry->rid = (UINT32)dwRid;

    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->account_name,
                                        pObject->Name);
    BAIL_ON_NT_STATUS(ntStatus);

    pDisplayEntry->account_flags = SamDbMapDatabaseToSamrFlags(
                                    pObject->Info.User.UserAccountControl,
                                    NULL);
    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->full_name,
                                        pObject->Info.User.FullName);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->description,
                                        pObject->Info.User.Description);
    BAIL_ON_NT_STATUS(ntStatus);

done:
    *pdwSize  = dwSize;

cleanup:
    return ntStatus;

error:
    if (pInfo1 && pInfo1->entries) {
        SamrSrvFreeMemory(pInfo1->entries);
        pInfo1->entries = NULL;
    }

    goto cleanup;
}


static
NTSTATUS
SamrSrvFillDisplayInfoGeneral(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfo *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSID pSid = NULL;
    ULONG dwRid = 0;
    SamrDisplayInfoGeneral *pInfo2 = NULL;
    SamrDisplayEntryGeneral *pDisplayEntry = NULL;
    DWORD dwSize = 0;

    if (pObject->Type != SAMDB_OBJECT_TYPE_USER)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS (ntStatus);
    }

    dwSize  = (*pdwSize);
    dwSize += sizeof(pInfo->info2.entries[0]);
    dwSize += wc16slen(pObject->Name) * sizeof(WCHAR);

    if (pObject->Info.User.Description)
    {
        dwSize += wc16slen(pObject->Info.User.Description) * sizeof(WCHAR);
    }

    /* If NULL pointer is passed we're just calculating the size */
    if (pInfo == NULL) goto done;
    pInfo2 = &pInfo->info2;

    if (!pInfo2->entries) {
        ntStatus = SamrSrvAllocateMemory(
                            (void**)&pInfo2->entries,
                            sizeof(pInfo2->entries[0]) * dwCount);
        pInfo2->count = dwCount;
    }

    pDisplayEntry = &(pInfo2->entries[i]);

    //pDisplayEntry->idx           = (UINT32)llRecId;
    pDisplayEntry->idx = i;

    pSid = pObject->Sid;
    dwRid = pSid->SubAuthority[pSid->SubAuthorityCount - 1];

    pDisplayEntry->rid           = (UINT32)dwRid;

    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->account_name,
                                        pObject->Name);
    BAIL_ON_NT_STATUS(ntStatus);

    pDisplayEntry->account_flags = SamDbMapDatabaseToSamrFlags(
                                    pObject->Info.User.UserAccountControl,
                                    NULL);

    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->description,
                                        pObject->Info.User.Description);
    BAIL_ON_NT_STATUS(ntStatus);

done:
    *pdwSize  = dwSize;

cleanup:
    return ntStatus;

error:
    if (pInfo2 && pInfo2->entries) {
        SamrSrvFreeMemory(pInfo2->entries);
        pInfo2->entries = NULL;
    }

    goto cleanup;
}


static
NTSTATUS
SamrSrvFillDisplayInfoGeneralGroups(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfo *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSID pSid = NULL;
    ULONG dwRid = 0;
    DWORD dwGroupAttributes = 0;
    SamrDisplayInfoGeneralGroups *pInfo3 = NULL;
    SamrDisplayEntryGeneralGroup *pDisplayEntry = NULL;
    DWORD dwSize = 0;

    if (pObject->Type != SAMDB_OBJECT_TYPE_LOCAL_GROUP)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS (ntStatus);
    }

    dwSize  = (*pdwSize);
    dwSize += sizeof(pInfo->info3.entries[0]);
    dwSize += wc16slen(pObject->Name) * sizeof(WCHAR);

    if (pObject->Info.LocalGroup.Description)
    {
        dwSize +=
            wc16slen(pObject->Info.LocalGroup.Description) * sizeof(WCHAR);
    }

    /* If NULL pointer is passed we're just calculating the size */
    if (pInfo == NULL) goto done;
    pInfo3 = &pInfo->info3;

    if (!pInfo3->entries) {
        ntStatus = SamrSrvAllocateMemory(
                           (void**)&pInfo3->entries,
                           sizeof(pInfo3->entries[0]) * dwCount);
        pInfo3->count = dwCount;
    }

    pDisplayEntry = &(pInfo3->entries[i]);

    //pDisplayEntry->idx           = (UINT32)llRecId;
    pDisplayEntry->idx = i;

    pSid = pObject->Sid;
    dwRid = pSid->SubAuthority[pSid->SubAuthorityCount - 1];

    pDisplayEntry->rid           = (UINT32)dwRid;

    /* TODO: Add support for group attributes when it's time
       for domain groups */
    pDisplayEntry->account_flags = (UINT32)dwGroupAttributes;

    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->account_name,
                                        pObject->Name);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus = SamrSrvInitUnicodeString(&pDisplayEntry->description,
                                        pObject->Info.LocalGroup.Description);
    BAIL_ON_NT_STATUS(ntStatus);

done:
    *pdwSize  = dwSize;

cleanup:
    return ntStatus;

error:
    if (pInfo3 && pInfo3->entries) {
        SamrSrvFreeMemory(pInfo3->entries);
        pInfo3->entries = NULL;
    }

    goto cleanup;
}


static
NTSTATUS
SamrSrvFillDisplayInfoAscii(
    PDOMAIN_CONTEXT pDomCtx,
    PSAMDB_OBJECT_INFO pObject,
    SamrDisplayInfoAscii *pInfo,
    DWORD i,
    DWORD dwCount,
    PDWORD pdwSize
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    SamrDisplayEntryAscii *pDisplayEntry = NULL;
    DWORD dwSize = 0;
    DWORD dwUsernameLen = 0;

    dwUsernameLen = wc16slen(pObject->Name);

    dwSize  = (*pdwSize);
    dwSize += sizeof(pInfo->entries[0]);
    dwSize += (dwUsernameLen + 1) * sizeof(CHAR);

    /* If NULL pointer is passed we're just calculating the size */
    if (pInfo == NULL) goto done;

    if (!pInfo->entries) {
        ntStatus = SamrSrvAllocateMemory(
                             (void**)&pInfo->entries,
                             sizeof(pInfo->entries[0]) * dwCount);
        pInfo->count = dwCount;
    }

    pDisplayEntry = &(pInfo->entries[i]);

    //pDisplayEntry->idx = (UINT32)llRecId;
    pDisplayEntry->idx = i;

    pDisplayEntry->account_name.Length        = dwUsernameLen;
    pDisplayEntry->account_name.MaximumLength = dwUsernameLen;

    ntStatus = SamrSrvAllocateMemory(
                       (void**)&pDisplayEntry->account_name.Buffer,
                       (dwUsernameLen + 1) * sizeof(CHAR));
    BAIL_ON_NT_STATUS(ntStatus);

    wc16stombs(pDisplayEntry->account_name.Buffer,
               pObject->Name,
               dwUsernameLen + 1);

done:
    *pdwSize  = dwSize;

cleanup:
    return ntStatus;

error:
    if (pInfo && pInfo->entries) {
        SamrSrvFreeMemory(pInfo->entries);
        pInfo->entries = NULL;
    }

    goto cleanup;
}


/*
local variables:
mode: c
c-basic-offset: 4
indent-tabs-mode: nil
tab-width: 4
end:
*/
