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

#include "includes.h"


NTSTATUS
SamrSrvEnumDomains(
    IN  handle_t        hBinding,
    IN  CONNECT_HANDLE  hConn,
    IN OUT PDWORD       pdwResume,
    IN  DWORD           dwMaxSize,
    OUT ENTRY_ARRAY   **ppDomains,
    OUT PDWORD          pdwNumEntries
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    NTSTATUS ntEnumStatus = STATUS_SUCCESS;
    DWORD dwError = ERROR_SUCCESS;
    PCONNECT_CONTEXT pConnCtx = NULL;
    SAMDB_ENUM_HANDLE enumHandle = NULL;
    SAMDB_OBJECT_TYPE ObjectType = SAMDB_OBJECT_TYPE_DOMAIN;
    PSAMDB_OBJECT_INFO *ppObjects = NULL;
    DWORD entriesCount = 0;
    PSAMDB_OBJECT_INFO pObject = NULL;
    ENTRY_ARRAY *pDomains = NULL;
    PENTRY pEntry = NULL;
    DWORD dwObjectsCount = 0;
    DWORD dwTotalSize = 0;
    DWORD resumeIndex = 0;
    DWORD domainIndex = 0;
    DWORD objectIndex = 0;

    BAIL_ON_INVALID_PTR(hBinding);
    BAIL_ON_INVALID_PTR(hConn);
    BAIL_ON_INVALID_PTR(pdwResume);
    BAIL_ON_INVALID_PTR(ppDomains);
    BAIL_ON_INVALID_PTR(pdwNumEntries);

    pConnCtx = (PCONNECT_CONTEXT)hConn;

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

    /* Check access rights required */
    if (!(pConnCtx->dwAccessGranted & SAMR_ACCESS_ENUM_DOMAINS))
    {
        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 (pConnCtx->DomainEnumHandle)
        {
            SamDbCloseEnum(pConnCtx->DomainEnumHandle);
            pConnCtx->DomainEnumHandle = NULL;
        }

        dwError = SamDbOpenEnumObjects(NULL,
                                       ObjectType,
                                       SAMDB_ENUM_SORT_ORDER_NONE,
                                       &enumHandle);
        BAIL_ON_LSA_ERROR(dwError);

        pConnCtx->DomainEnumHandle   = enumHandle;
        pConnCtx->DomainEnumResumeAt = resumeIndex;

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

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

    dwTotalSize += sizeof(pDomains);

    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(
                             pConnCtx->DomainEnumHandle,
                             dwMaxSize,
                             &dwObjectsCount,
                             &ppObjects);
        BAIL_ON_LSA_ERROR(dwError);

        entriesCount = dwObjectsCount;

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

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

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

    domainIndex = 0;
    while (dwTotalSize < dwMaxSize &&
           domainIndex < entriesCount &&
           (pConnCtx->DomainEnumHandle || objectIndex < dwObjectsCount))
    {
        pEntry = &pDomains->pEntries[domainIndex];

        if (!ppObjects && pConnCtx->DomainEnumHandle)
        {
            //
            // 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(
                                pConnCtx->DomainEnumHandle,
                                1,
                                &dwObjectsCount,
                                &ppObjects);
            if (dwError == ERROR_SUCCESS ||
                dwError == ERROR_NO_MORE_ITEMS)
            {
                SamDbCloseEnum(pConnCtx->DomainEnumHandle);
                pConnCtx->DomainEnumHandle   = NULL;
                pConnCtx->DomainEnumResumeAt = 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++];

        pEntry->dwIndex = domainIndex;

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

        if (dwObjectsCount == 1)
        {
            SamDbFreeObjects(dwObjectsCount, ppObjects);

            ppObjects = NULL;
            dwObjectsCount = 0;
            objectIndex = 0;
        }

        dwTotalSize += sizeof(*pEntry);
        dwTotalSize += pEntry->Name.MaximumLength;
        domainIndex++;
    }

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

    }
    else if (pConnCtx->DomainEnumHandle)
    {
        ntEnumStatus = STATUS_MORE_ENTRIES;
    }

    pDomains->dwCount = domainIndex;

    resumeIndex += domainIndex;
    pConnCtx->DomainEnumResumeAt = resumeIndex;

    *pdwResume = resumeIndex;
    *pdwNumEntries = domainIndex;
    *ppDomains = pDomains;

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

                SamrSrvFreeMemory(pDomains->pEntries);
            }

            SamrSrvFreeMemory(pDomains);
        }

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

        *pdwResume      = 0;
        *pdwNumEntries  = 0;
        *ppDomains      = 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:
*/
