#include "RBC9-SpaceNav.h"


static HANDLE open_registry_subkey(IN PWSTR subkey)
{
	WCHAR buf[256];
	UNICODE_STRING path;
	OBJECT_ATTRIBUTES obj_attr;
	HANDLE key;
	NTSTATUS nt_ret;

	DBG_ENTER(("\"%ws\"", subkey));

	RtlZeroMemory(buf, sizeof(buf));
	path.Length = 0;
	path.MaximumLength = sizeof(buf);
	path.Buffer = buf;

	RtlAppendUnicodeToString(&path, REGISTRY_BASE_PATH);
	RtlAppendUnicodeToString(&path, L"\\");
	RtlAppendUnicodeToString(&path, subkey);

	InitializeObjectAttributes(&obj_attr, &path,
		OBJ_CASE_INSENSITIVE, NULL, NULL);

	nt_ret = ZwOpenKey(&key, KEY_ALL_ACCESS, &obj_attr);
	if(! NT_SUCCESS(nt_ret)) {
		DBG_LEAVE(("NULL: ZwOpenKey failed: %x", nt_ret));
		return NULL;
	}

	DBG_LEAVE(("%p", key));
	return key;
}


NTSTATUS RBC9_Reg_Test()
{
	NTSTATUS				Status=STATUS_SUCCESS;
	HANDLE					key;
	PKEY_FULL_INFORMATION	MyKeyList;
	PKEY_BASIC_INFORMATION	MySubKey;
	ULONG					size;
	int						BclProfil;

	DBG_ENTER((" Get Registre "));

	/* open subkey */
	key = open_registry_subkey("");
	if(key == NULL) {
		DBG_LEAVE(("STATUS_OBJECT_NAME_NOT_FOUND"));
		return STATUS_OBJECT_NAME_NOT_FOUND;
	}

	Status = ZwQueryKey (key,KeyFullInformation,NULL,0,&size);
	if(! NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL) 
	{
		ZwClose(key);
		DBG_LEAVE(("%x", Status));
		return Status;
	}
	MyKeyList = (PKEY_FULL_INFORMATION)ExAllocatePool(NonPagedPool, size);
	if(MyKeyList == NULL) {
		ZwClose(key);
		DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}
	Status = ZwQueryKey (key,KeyFullInformation,MyKeyList,size,&size);
	if(! NT_SUCCESS(Status)) 
	{
		ExFreePool(MyKeyList);
		ZwClose(key);
		DBG_LEAVE(("%x", Status));
		return Status;
	}
	
	DBG_OUT(("MyKeyList %d %d",MyKeyList->SubKeys,MyKeyList->MaxNameLen));


	for (BclProfil = 0;BclProfil < MyKeyList->SubKeys;BclProfil++)
	{
		Status = ZwEnumerateKey  (key,BclProfil,KeyBasicInformation,NULL,0,&size);
		if(! NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL) 
		{
			ExFreePool(MyKeyList);
			ZwClose(key);
			DBG_LEAVE(("%x", Status));
			return Status;
		}
		MySubKey = (PKEY_BASIC_INFORMATION)ExAllocatePool(NonPagedPool, size+1);
		if(MySubKey == NULL) {
			ExFreePool(MyKeyList);
			ZwClose(key);
			DBG_LEAVE(("STATUS_INSUFFICIENT_RESOURCES"));
			return STATUS_INSUFFICIENT_RESOURCES;
		}


		Status = ZwEnumerateKey  (key,BclProfil,KeyBasicInformation,MySubKey,size,&size);
		if(! NT_SUCCESS(Status)) 
		{
			ExFreePool(MySubKey);
			ExFreePool(MyKeyList);
			ZwClose(key);
			DBG_LEAVE(("%x", Status));
			return Status;
		}

		MySubKey->Name[MySubKey->NameLength]=0;
		
		DBG_OUT(("SubKey %d %d %ws",BclProfil,MySubKey->NameLength,MySubKey->Name));

		ExFreePool(MySubKey);
	}

	ExFreePool(MyKeyList);
	ZwClose(key);

	DBG_LEAVE(("Fin OK %x",Status));

}