// API should have failed with insufficient buffer.
if (fAPISuccess)
__leave;
else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
_tprintf(TEXT("LookupAccountName() failed. Error %d\n"),
GetLastError());
__leave;
}
pUserSID = myheapalloc(cbUserSID);
if (!pUserSID) {
_tprintf(TEXT("HeapAlloc() failed. Error %d\n"), GetLastError());
__leave;
}
szDomain = (TCHAR *) myheapalloc(cbDomain * sizeof(TCHAR));
if (!szDomain) {
_tprintf(TEXT("HeapAlloc() failed. Error %d\n"), GetLastError());
__leave;
}
fAPISuccess = LookupAccountName(NULL, lpszAccountName,
pUserSID, &cbUserSID, szDomain, &cbDomain, &snuType);
if (!fAPISuccess) {
_tprintf(TEXT("LookupAccountName() failed. Error %d\n"),
GetLastError());
__leave;
}
//
// STEP 2: Get security descriptor (SD) of the file specified.
//
fAPISuccess = GetFileSecurity(lpszFileName,
secInfo, pFileSD, 0, &cbFileSD);
// API should have failed with insufficient buffer.
if (fAPISuccess)
__leave;
else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
_tprintf(TEXT("GetFileSecurity() failed. Error %d\n"),
GetLastError());
__leave;
}
pFileSD = myheapalloc(cbFileSD);
if (!pFileSD) {
_tprintf(TEXT("HeapAlloc() failed. Error %d\n"), GetLastError());
__leave;
}
fAPISuccess = GetFileSecurity(lpszFileName,
secInfo, pFileSD, cbFileSD, &cbFileSD);
if (!fAPISuccess) {
_tprintf(TEXT("GetFileSecurity() failed. Error %d\n"),
GetLastError());
__leave;
}
//
// STEP 3: Initialize new SD.
//
if (!InitializeSecurityDescriptor(&newSD,
SECURITY_DESCRIPTOR_REVISION)) {
_tprintf(TEXT("InitializeSecurityDescriptor() failed.")
TEXT("Error %d\n"), GetLastError());
__leave;
}
//
// STEP 4: Get DACL from the old SD.
//
if (!GetSecurityDescriptorDacl(pFileSD, &fDaclPresent, &pACL,
&fDaclDefaulted)) {
_tprintf(TEXT("GetSecurityDescriptorDacl() failed. Error %d\n"),
GetLastError());
__leave;
}
//
// STEP 5: Get size information for DACL.
//
AclInfo.AceCount = 0; // Assume NULL DACL.
AclInfo.AclBytesFree = 0;
AclInfo.AclBytesInUse = sizeof(ACL);
if (pACL == NULL)
fDaclPresent = FALSE;
// If not NULL DACL, gather size information from DACL.
if (fDaclPresent) {
if (!GetAclInformation(pACL, &AclInfo,
sizeof(ACL_SIZE_INFORMATION), AclSizeInformation)) {
_tprintf(TEXT("GetAclInformation() failed. Error %d\n"),
GetLastError());
__leave;
}
}
//
// STEP 6: Compute size needed for the new ACL.
//
cbNewACL = AclInfo.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE)
+ GetLengthSid(pUserSID) - sizeof(DWORD);
//
// STEP 7: Allocate memory for new ACL.
//
pNewACL = (PACL) myheapalloc(cbNewACL);
if (!pNewACL) {
_tprintf(TEXT("HeapAlloc() failed. Error %d\n"), GetLastError());
__leave;
}
//
// STEP 8: Initialize the new ACL.
//
if (!InitializeAcl(pNewACL, cbNewACL, ACL_REVISION2)) {
_tprintf(TEXT("InitializeAcl() failed. Error %d\n"),
GetLastError());
__leave;
}
//
// STEP 9 If DACL is present, copy all the ACEs from the old DACL
// to the new DACL.
//
// The following code assumes that the old DACL is
// a