-
Notifications
You must be signed in to change notification settings - Fork 3
/
delete_file.cpp
92 lines (74 loc) · 2.22 KB
/
delete_file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* This file is a part of the source code of "byenow" program.
*
* Copyright (c) 2020- Alexander Pankratov and IO Bureau SA.
* All rights reserved.
*
* The source code is distributed under the terms of 2-clause
* BSD license with the Commons Clause condition. See LICENSE
* file for details.
*/
#include "delete_file.h"
#include "libp/_elpify.h"
#include "libp/_system_api.h"
#include "libp/_ntstatus.h"
#define HSRO (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN)
//
static
bool delete_file_win32(const wstring & file, dword attrs, api_error_cb * err)
{
if (elp->DeleteFile(file.c_str()))
return true;
if (GetLastError() == ERROR_FILE_NOT_FOUND)
return true;
__on_api_error("DeleteFile", file);
return false;
}
static
bool delete_file_ntapi(const wstring & file, dword attrs, api_error_cb * err)
{
UNICODE_STRING name;
OBJECT_ATTRIBUTES attr;
NTSTATUS status;
status = ntdll.RtlDosPathNameToNtPathName_U_WithStatus(elpify(file).c_str(), &name, NULL, NULL);
if (status != STATUS_SUCCESS)
{
__on_api_error_ex("RtlDosPathNameToNtPathName_U", status, file);
return false;
}
InitializeObjectAttributes(&attr, &name, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ntdll.NtDeleteFile(&attr);
ntdll.RtlFreeUnicodeString(&name);
if (status == STATUS_SUCCESS)
return true;
if (status == 0xC0000034) // STATUS_OBJECT_NAME_NOT_FOUND
return false;
__on_api_error_ex("NtDeleteFile", status, file);
return false;
}
bool delete_file(const wstring & file, dword attrs, bool ntapi, api_error_cb * err)
{
if ( (attrs & HSRO) &&
! elp->SetFileAttributes(file.c_str(), attrs & ~HSRO))
{
__on_api_error("SetFileAttributes", file);
}
return ntapi ? delete_file_ntapi(file, attrs, err)
: delete_file_win32(file, attrs, err);
}
//
bool delete_folder(const wstring & folder, dword attrs, api_error_cb * err)
{
if ( (attrs & HSRO) &&
! elp->SetFileAttributes(folder.c_str(), attrs & ~HSRO))
{
__on_api_error("SetFileAttributes", folder);
}
if (elp->RemoveDirectory(folder.c_str()))
return true;
if (GetLastError() == ERROR_FILE_NOT_FOUND ||
GetLastError() == ERROR_PATH_NOT_FOUND)
return true;
__on_api_error("RemoveDirectory", folder);
return false;
}