/* -*- 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:
 *
 *        samdbcallback.c
 *
 * Abstract:
 *
 *
 *      Likewise SAM Database Provider
 *
 *      SAM object notify callbacks registration
 *
 * Authors: Rafal Szczesniak (rafal@likewise.com)
 *
 */

#include "includes.h"


static
VOID
SamDbFreeCallbackRegistration(
    PSAMDB_CALLBACK_REGISTRATION Registration
    );


DWORD
SamDbRegisterCallback(
    OUT PSAMDB_CALLBACK_REGISTRATION* Registration,
    IN PVOID Context,
    IN PSID ObjectSid,
    IN BOOLEAN IsPrefix,
    IN SAMDB_RELOAD_CALLBACK ReloadCallback
    )
{
    DWORD error = ERROR_SUCCESS;
    NTSTATUS ntStatus = STATUS_SUCCESS;
    BOOLEAN inLock = FALSE;
    PSAMDB_CALLBACK_REGISTRATION callbackRecord = NULL;

    BAIL_ON_INVALID_POINTER(ReloadCallback, error);

    error = LwAllocateMemory(
                      sizeof(*callbackRecord),
                      OUT_PPVOID(&callbackRecord));
    BAIL_ON_SAMDB_ERROR(error);

    if (ObjectSid)
    {
        ntStatus = RtlDuplicateSid(
                          &callbackRecord->ObjectSid,
                          ObjectSid);
        BAIL_ON_NT_STATUS(ntStatus);
    }

    callbackRecord->IsPrefix    = IsPrefix;
    callbackRecord->Context     = Context;
    callbackRecord->CallbackFn  = ReloadCallback;

    LwListInit(&callbackRecord->Record);

    SAMDB_EXCLUSIVE_LOCK_RWLOCK(inLock, pgSamDbGlobals->pRwLock);

    LwListInsertAfter(
             &pgSamDbGlobals->NotifyCallbacks,
             &callbackRecord->Record);

cleanup:
error:
    SAMDB_UNLOCK_RWLOCK(inLock, pgSamDbGlobals->pRwLock);

    *Registration = callbackRecord;

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

    return error;
}


VOID
SamDbUnregisterCallback(
    IN PSAMDB_CALLBACK_REGISTRATION Registration
    )
{
    BOOLEAN inLock = FALSE;
    PLW_LIST_LINKS currentRecord = NULL;
    PSID objectSid = Registration->ObjectSid;
    BOOLEAN isPrefix = Registration->IsPrefix;
    SAMDB_RELOAD_CALLBACK callbackFn = Registration->CallbackFn;
    PSAMDB_CALLBACK_REGISTRATION callbackRegistration = NULL;

    SAMDB_EXCLUSIVE_LOCK_RWLOCK(inLock, pgSamDbGlobals->pRwLock);

    while ((currentRecord = LwListTraverse(
                                  &pgSamDbGlobals->NotifyCallbacks,
                                  currentRecord)) != NULL)
    {
        callbackRegistration = LW_STRUCT_FROM_FIELD(
                                     currentRecord,
                                     SAMDB_CALLBACK_REGISTRATION,
                                     Record);

        if (objectSid == callbackRegistration->ObjectSid &&
            isPrefix == callbackRegistration->IsPrefix &&
            callbackFn == callbackRegistration->CallbackFn)
        {
            LwListRemove(currentRecord);

            callbackRegistration = (PSAMDB_CALLBACK_REGISTRATION)currentRecord;
            SamDbFreeCallbackRegistration(callbackRegistration);

            currentRecord = NULL;
            callbackRegistration = NULL;

            break;
        }
    }

    SAMDB_UNLOCK_RWLOCK(inLock, pgSamDbGlobals->pRwLock);
}


static
VOID
SamDbFreeCallbackRegistration(
    PSAMDB_CALLBACK_REGISTRATION Registration
    )
{
    RTL_FREE(&Registration->ObjectSid);
    Registration->Context = NULL;
    Registration->CallbackFn = NULL;

    LW_SAFE_FREE_MEMORY(Registration);
}


VOID
SamDbNotifyCallbacks(
    IN PSID ObjectSid
    )
{
    BOOLEAN inLock = FALSE;
    PLW_LIST_LINKS currentRecord = NULL;
    PSAMDB_CALLBACK_REGISTRATION callbackRegistration = NULL;

    SAMDB_SHARED_LOCK_RWLOCK(inLock, pgSamDbGlobals->pRwLock);

    while ((currentRecord = LwListTraverse(
                                  &pgSamDbGlobals->NotifyCallbacks,
                                  currentRecord)) != NULL)
    {
        callbackRegistration = LW_STRUCT_FROM_FIELD(
                                     currentRecord,
                                     SAMDB_CALLBACK_REGISTRATION,
                                     Record);
        //
        // 1. If callbacks has been registered for NULL SID, then
        //    it is called upon every single change.
        // 2. If SID has been set along with IsPrefix = TRUE then
        //    it is called upon every change in that SID and all
        //    other SIDs it is a prefix of.
        // 3. If SID has been set but IsPrefix is FALSE then it is
        //    called everytime this exact SID changes.
        //
        if (callbackRegistration->ObjectSid == NULL ||
            RtlEqualSid(
                    ObjectSid,
                    callbackRegistration->ObjectSid) ||
            (callbackRegistration->IsPrefix &&
             RtlIsPrefixSid(
                    callbackRegistration->ObjectSid,
                    ObjectSid)))
        {
            callbackRegistration->CallbackFn(
                        callbackRegistration->Context,
                        ObjectSid);
        }
    }

    SAMDB_UNLOCK_RWLOCK(inLock, pgSamDbGlobals->pRwLock);
}


VOID
SamDbFreeCallbackRegistrations(
    VOID
    )
{
    PLW_LIST_LINKS record = NULL;
    PSAMDB_CALLBACK_REGISTRATION registration = NULL;

    while (!LwListIsEmpty(&pgSamDbGlobals->NotifyCallbacks))
    {
        record = LwListRemoveHead(&pgSamDbGlobals->NotifyCallbacks);

        registration = LW_STRUCT_FROM_FIELD(
                             record,
                             SAMDB_CALLBACK_REGISTRATION,
                             Record);
        SamDbFreeCallbackRegistration(registration);
    }
}
