/* -*- 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:
 *
 *        samdbcontext.c
 *
 * Abstract:
 *
 *
 *      Likewise SAM Database Provider
 *
 *      Provider context initialisation routines
 *
 * Authors: Krishna Ganugapati (krishnag@likewise.com)
 *          Sriram Nambakam (snambakam@likewise.com)
 *          Rafal Szczesniak (rafal@likewise.com)
 *
 */

#include "includes.h"


static
VOID
SamDbFreeContext(
    PSAMDB_CONTEXT DbContext
    );


DWORD
SamDbAcquireContext(
    PSAMDB_CONTEXT* pDbContext
    )
{
    DWORD error = ERROR_SUCCESS;
    BOOLEAN bInLock = FALSE;
    PSAMDB_CONTEXT dbContext = NULL;

    if (!pgSamDbGlobals)
    {
        // This is the very first SamDb call because globals are
        // not initialised yet
        error = SamDbInitGlobals(&gSamDbGlobals);
        BAIL_ON_SAMDB_ERROR(error);

        pgSamDbGlobals = &gSamDbGlobals;
    }

    SAMDB_LOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);

    error = SamDbAcquireContext_inlock(
                        &dbContext);
    BAIL_ON_SAMDB_ERROR(error);

cleanup:
    SAMDB_UNLOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);

    if (error)
    {
        if (dbContext)
        {
            SamDbFreeContext(dbContext);
            dbContext = NULL;
        }
    }

    *pDbContext = dbContext;

    return error;
}


DWORD
SamDbAcquireContext_inlock(
    PSAMDB_CONTEXT *pDbContext
    )
{
    DWORD error = ERROR_SUCCESS;
    PSAMDB_CONTEXT dbContext = NULL;

    if (gSamDbGlobals.DbContextList)
    {
        dbContext = gSamDbGlobals.DbContextList;

        gSamDbGlobals.DbContextList = gSamDbGlobals.DbContextList->Next;
        gSamDbGlobals.NumDbContexts--;

        dbContext->Next = NULL;
    }

    if (!dbContext)
    {
        error = SamDbInitContext(&dbContext);
        BAIL_ON_SAMDB_ERROR(error);
    }

    //
    // Ensure acquired context can use global variables
    //
    InterlockedIncrement(&gSamDbGlobals.ReferenceCount);

cleanup:
    *pDbContext = dbContext;

    return error;
}


VOID
SamDbReleaseContext(
    PSAMDB_CONTEXT DbContext
    )
{
    BOOLEAN bInLock = FALSE;

    SAMDB_LOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);

    SamDbReleaseContext_inlock(DbContext);

    SAMDB_UNLOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);

    if (gSamDbGlobals.ReferenceCount == 0)
    {
        SamDbCleanupLibraryInternal();
    }
}


VOID
SamDbReleaseContext_inlock(
    PSAMDB_CONTEXT DbContext
    )
{
    if (gSamDbGlobals.NumDbContexts < gSamDbGlobals.MaxNumDbContexts)
    {
        DbContext->Next = gSamDbGlobals.DbContextList;
        gSamDbGlobals.DbContextList = DbContext;

        gSamDbGlobals.NumDbContexts++;
    }
    else
    {
        SamDbFreeContext(DbContext);
    }

    //
    // This context no longer needs to use global variables
    //
    InterlockedDecrement(&gSamDbGlobals.ReferenceCount);
}


static
VOID
SamDbFreeContext(
    PSAMDB_CONTEXT DbContext
    )
{
    if (DbContext->DbHandle)
    {
        sqlite3_close(DbContext->DbHandle);
    }

    LW_SAFE_FREE_MEMORY(DbContext);
}


VOID
SamDbFreeContextList(
    VOID
    )
{
    PSAMDB_CONTEXT dbContext = pgSamDbGlobals->DbContextList;

    while (dbContext)
    {
        pgSamDbGlobals->DbContextList = dbContext->Next;
        dbContext->Next = NULL;

        SamDbFreeContext(dbContext);

        pgSamDbGlobals->NumDbContexts--;
        dbContext = pgSamDbGlobals->DbContextList;
    }
}


DWORD
SamDbGetLocalDomainSid(
    PSID* pSid
    )
{
    DWORD error = ERROR_SUCCESS;
    NTSTATUS ntStatus = STATUS_SUCCESS;
    BOOLEAN bInRwLock = FALSE;
    BOOLEAN bInLock = FALSE;
    PSAMDB_CONTEXT dbContext = NULL;
    DWORD localDomainSidLength = 0;
    PSID localDomainSid = NULL;

    SAMDB_SHARED_LOCK_RWLOCK(bInRwLock, gSamDbGlobals.pRwLock);

    if (!gSamDbGlobals.LocalDomainSid)
    {
        SAMDB_LOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);

        //
        // Make a copy of local domain SID. It will be needed many
        // times so it's more efficient to make a copy once instead
        // of accessing the database everytime it is needed.
        //
        error = SamDbAcquireContext_inlock(&dbContext);
        BAIL_ON_SAMDB_ERROR(error);

        error = SamDbGetLocalDomainSidInternal(
                           dbContext,
                           &localDomainSid);
        BAIL_ON_SAMDB_ERROR(error);

        SamDbReleaseContext_inlock(dbContext);
        dbContext = NULL;

        SAMDB_UNLOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);

        SAMDB_EXCLUSIVE_LOCK_RWLOCK(bInRwLock, gSamDbGlobals.pRwLock);
        gSamDbGlobals.LocalDomainSid = localDomainSid;
        localDomainSid = NULL;
    }

    localDomainSidLength = RtlLengthSid(
                               gSamDbGlobals.LocalDomainSid);
    error = LwAllocateMemory(
                    localDomainSidLength,
                    OUT_PPVOID(&localDomainSid));
    BAIL_ON_SAMDB_ERROR(error);

    ntStatus = RtlCopySid(
                    localDomainSidLength,
                    localDomainSid,
                    gSamDbGlobals.LocalDomainSid);
    BAIL_ON_NT_STATUS(ntStatus);

cleanup:
error:
    SAMDB_UNLOCK_MUTEX(bInLock, gSamDbGlobals.pMutex);
    SAMDB_UNLOCK_RWLOCK(bInRwLock, gSamDbGlobals.pRwLock);

    if (error || ntStatus)
    {
        LW_SAFE_FREE_MEMORY(localDomainSid);
    }

    if (dbContext)
    {
        SamDbReleaseContext(dbContext);
    }

    if (error == ERROR_SUCCESS &&
        ntStatus != STATUS_SUCCESS)
    {
        error = LwNtStatusToWin32Error(ntStatus);
    }

    *pSid = localDomainSid;

    return error;
}


DWORD
SamDbGetLocalDomainSidInternal(
    PSAMDB_CONTEXT DbContext,
    PSID* pSid
    )
{
    DWORD error = ERROR_SUCCESS;
    NTSTATUS ntStatus = STATUS_SUCCESS;
    SAMDB_ENUM_HANDLE enumHandle = NULL;
    DWORD maxCount = (DWORD)-1;
    DWORD domainsCount = 0;
    PSAMDB_OBJECT_INFO *domains = NULL;
    DWORD domainIndex = 0;
    DWORD localDomainSidLength = 0;
    PSID localDomainSid = NULL;

    error = SamDbOpenEnumObjectsInternal(
                    DbContext,
                    NULL,
                    SAMDB_OBJECT_TYPE_DOMAIN,
                    SAMDB_ENUM_SORT_ORDER_NONE,
                    &enumHandle);
    BAIL_ON_SAMDB_ERROR(error);

    error = SamDbEnumObjects(
                    enumHandle,
                    maxCount,
                    &domainsCount,
                    &domains);
    BAIL_ON_SAMDB_ERROR(error);

    for (domainIndex = 0;
         domainIndex < domainsCount;
         domainIndex++)
    {
        if (domains[domainIndex]->Sid->SubAuthorityCount == 1)
        {
            // This is BUILTIN domain object so skip it
            continue;
        }

        localDomainSidLength = RtlLengthSid(
                                   domains[domainIndex]->Sid);
        error = LwAllocateMemory(
                        localDomainSidLength,
                        OUT_PPVOID(&localDomainSid));
        BAIL_ON_SAMDB_ERROR(error);

        ntStatus = RtlCopySid(
                        localDomainSidLength,
                        localDomainSid,
                        domains[domainIndex]->Sid);
        BAIL_ON_NT_STATUS(ntStatus);

        break;
    }

cleanup:
error:
    if (error || ntStatus)
    {
        LW_SAFE_FREE_MEMORY(localDomainSid);
    }

    if (enumHandle)
    {
        SamDbCloseEnumInternal(enumHandle);
    }

    if (domains)
    {
        SamDbFreeObjects(
                  domainsCount,
                  domains);
    }

    if (error == ERROR_SUCCESS &&
        ntStatus != STATUS_SUCCESS)
    {
        error = LwNtStatusToWin32Error(ntStatus);
    }

    *pSid = localDomainSid;

    return error;
}
