/* 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_enumdomainaccounts.c
 *
 * Abstract:
 *
 *        Remote Procedure Call (RPC) Server Interface
 *
 *        SamrEnumDomainAccounts function
 *
 * Authors: Rafal Szczesniak (rafal@likewise.com)
 */

#include "includes.h"


NTSTATUS
SamrSrvEnumDomainAccounts(
    IN  handle_t          hBinding,
    IN  DOMAIN_HANDLE     hDomain,
    IN OUT PDWORD         pdwResume,
    IN  SAMDB_OBJECT_TYPE ObjectType,
    IN  DWORD             dwFlagsFilter,
    IN  DWORD             dwMaxSize,
    OUT RID_NAME_ARRAY  **ppNames,
    OUT UINT32           *pdwNumEntries
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    NTSTATUS ntEnumStatus = STATUS_SUCCESS;
    DWORD dwError = ERROR_SUCCESS;
    SAMDB_ENUM_HANDLE enumHandle = NULL;
    DWORD dwObjectsCount = 0;
    PSAMDB_OBJECT_INFO *ppObjects = NULL;
    DWORD entriesCount = 0;
    PSAMDB_OBJECT_INFO pObject = NULL;
    PDOMAIN_CONTEXT pDomCtx = NULL;
    DWORD dwTotalSize = 0;
    DWORD resumeIndex = 0;
    DWORD accountIndex = 0;
    DWORD objectIndex = 0;
    SAMDB_UF_FLAGS accountFlagsFilter = 0;
    DWORD dwRid = 0;
    PRID_NAME pName = NULL;
    RID_NAME_ARRAY *pNames = NULL;

    BAIL_ON_INVALID_PTR(hDomain);
    BAIL_ON_INVALID_PTR(pdwResume);
    BAIL_ON_INVALID_PTR(ppNames);
    BAIL_ON_INVALID_PTR(pdwNumEntries);

    pDomCtx  = (PDOMAIN_CONTEXT)hDomain;

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

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

    //
    // If we're already in the midst of an enumeration, we'll have a handle.
    // Otherwise we need to open one.
    //
    resumeIndex = *pdwResume;
    if (resumeIndex == 0)
    {
        //
        // resumeIndex = 0 restarts the enumeration so close the enum
        // handle if there is one opened
        //
        if (pDomCtx->AccountEnumHandle)
        {
            SamDbCloseEnum(pDomCtx->AccountEnumHandle);
            pDomCtx->AccountEnumHandle = NULL;
        }

        dwError = SamDbOpenEnumObjects(pDomCtx->pDomainSid,
                                       ObjectType,
                                       SAMDB_ENUM_SORT_ORDER_NONE,
                                       &enumHandle);
        BAIL_ON_LSA_ERROR(dwError);

        pDomCtx->AccountEnumHandle   = enumHandle;
        pDomCtx->AccountEnumResumeAt = resumeIndex;

        objectIndex = 0;
        enumHandle = NULL;
    }
    else if (resumeIndex != 0 &&
             pDomCtx->AccountEnumResumeAt != resumeIndex)
    {
        dwError = ERROR_INVALID_DATA;
        BAIL_ON_LSA_ERROR(dwError);
    }

    ntStatus = SamrSrvAllocateMemory(
                         OUT_PPVOID(&pNames),
                         sizeof(*pNames));
    BAIL_ON_NT_STATUS(ntStatus);

    dwTotalSize += sizeof(pNames);

    if (dwMaxSize == (DWORD)-1)
    {
        //
        // The caller accepts as much data as needed so let's enumerate
        // everything and estimate how much space do we need
        //
        dwError = SamDbEnumObjects(
                             pDomCtx->AccountEnumHandle,
                             dwMaxSize,
                             &dwObjectsCount,
                             &ppObjects);
        BAIL_ON_LSA_ERROR(dwError);

        entriesCount = dwObjectsCount;

        SamDbCloseEnum(pDomCtx->AccountEnumHandle);
        pDomCtx->AccountEnumHandle = NULL;
    }
    else
    {
        //
        // There will be no more entries for sure because there's still
        // some space needed for names
        //
        entriesCount = dwMaxSize / sizeof(*pNames->pEntries);

        //
        // There has to be at least one entry to return
        //
        if (entriesCount == 0)
        {
            entriesCount = 1;
        }
    }

    ntStatus = SamrSrvAllocateMemory(
                         OUT_PPVOID(&pNames->pEntries),
                         sizeof(*pNames->pEntries) * entriesCount);
    BAIL_ON_NT_STATUS(ntStatus);

    accountIndex = 0;
    while (dwTotalSize < dwMaxSize &&
           accountIndex < entriesCount &&
           (pDomCtx->AccountEnumHandle || accountIndex < dwObjectsCount))
    {
        pName = &pNames->pEntries[accountIndex];

        if (!ppObjects)
        {
            //
            // Because we don't know how long each name is, and the caller
            // has set the size limit, get one at a time.
            //
            dwError = SamDbEnumObjects(
                                pDomCtx->AccountEnumHandle,
                                1,
                                &dwObjectsCount,
                                &ppObjects);
            if (dwError == ERROR_SUCCESS ||
                dwError == ERROR_NO_MORE_ITEMS)
            {
                SamDbCloseEnum(pDomCtx->AccountEnumHandle);
                pDomCtx->AccountEnumHandle   = NULL;
                pDomCtx->AccountEnumResumeAt = 0;

                if (dwError == ERROR_NO_MORE_ITEMS)
                {
                    dwError = ERROR_SUCCESS;
                    break;
                }

                dwError = ERROR_SUCCESS;
            }
            else if (dwError == ERROR_MORE_DATA)
            {
                dwError = ERROR_SUCCESS;
            }
            else
            {
                BAIL_ON_LSA_ERROR(dwError);
            }
        }

        pObject = ppObjects[objectIndex++];

        if (ObjectType == SAMDB_OBJECT_TYPE_USER && dwFlagsFilter)
        {
            SAMDB_USER_FLAGS remainingFlags = 0;

            accountFlagsFilter = SamDbMapSamrToDatabaseFlags(
                                      dwFlagsFilter,
                                      &remainingFlags);
        }

        if ((accountFlagsFilter &&
             pObject->Info.User.UserAccountControl & accountFlagsFilter) ||
            accountFlagsFilter == 0)
        {
            dwRid = pObject->Sid->SubAuthority[pObject->Sid->SubAuthorityCount - 1];
            pName->dwRid = (UINT32)dwRid;

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

            dwTotalSize += sizeof(*pName);
            dwTotalSize += pName->Name.MaximumLength;
            accountIndex++;
        }

        if (dwObjectsCount == 1)
        {
            SamDbFreeObjects(dwObjectsCount, ppObjects);
            ppObjects = NULL;
            dwObjectsCount = 0;
            objectIndex = 0;
        }
    }

    if (!pDomCtx->AccountEnumHandle &&
        accountIndex > 0)
    {
        // We are done with enumeration in this call
        ntEnumStatus = STATUS_SUCCESS;
    }
    else if (!pDomCtx->AccountEnumHandle &&
             accountIndex == 0)
    {
        // There's nothing left to enumerate
        ntEnumStatus = STATUS_NO_MORE_ENTRIES;

    }
    else if (pDomCtx->AccountEnumHandle)
    {
        ntEnumStatus = STATUS_MORE_ENTRIES;
    }

    pNames->dwCount = accountIndex;

    resumeIndex += accountIndex;
    pDomCtx->AccountEnumResumeAt = resumeIndex;

    *pdwResume      = resumeIndex;
    *pdwNumEntries  = accountIndex;
    *ppNames        = pNames;

error:
    if (ntStatus || dwError)
    {
        if (pNames)
        {
            if (pNames->pEntries)
            {
                for (accountIndex = 0;
                     accountIndex < pNames->dwCount;
                     accountIndex++)
                {
                    SamrSrvFreeUnicodeString(
                                   &(pNames->pEntries[accountIndex].Name));
                }

                SamrSrvFreeMemory(pNames->pEntries);
            }

            SamrSrvFreeMemory(pNames);
        }

        // If we hit an error, force enum to start over at the beginning
        if (pDomCtx->AccountEnumHandle)
        {
            SamDbCloseEnum(pDomCtx->AccountEnumHandle);
            pDomCtx->AccountEnumHandle   = NULL;
            pDomCtx->AccountEnumResumeAt = 0;
        }

        *pdwResume      = 0;
        *pdwNumEntries  = 0;
        *ppNames        = NULL;
    }

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

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

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

    return ntStatus;
}


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