Refactor headers
[wimlib] / programs / imagex-win32.c
1
2 /* Replacements for functions needed specifically by the 'imagex' program in
3  * Windows native builds; also, Windows-specific code to acquire and release
4  * privileges needed to backup and restore files */
5
6 #ifndef __WIN32__
7 #  error "This file contains Windows code"
8 #endif
9
10 #include "imagex-win32.h"
11 #include <windows.h>
12 #include <errno.h>
13 #include <string.h>
14 #include <assert.h>
15 #include <stdio.h>
16
17 /* Replacement for glob() in Windows native builds that operates on wide
18  * characters. */
19 int
20 win32_wglob(const wchar_t *pattern, int flags,
21             int (*errfunc)(const wchar_t *epath, int eerrno),
22             glob_t *pglob)
23 {
24         WIN32_FIND_DATAW dat;
25         DWORD err;
26         HANDLE hFind;
27         int ret;
28         size_t nspaces;
29
30         const wchar_t *backslash, *end_slash;
31         size_t prefix_len;
32
33         backslash = wcsrchr(pattern, L'\\');
34         end_slash = wcsrchr(pattern, L'/');
35
36         if (backslash > end_slash)
37                 end_slash = backslash;
38
39         if (end_slash)
40                 prefix_len = end_slash - pattern + 1;
41         else
42                 prefix_len = 0;
43
44         /* This function does not support all functionality of the POSIX glob(),
45          * so make sure the parameters are consistent with supported
46          * functionality. */
47         assert(errfunc == NULL);
48         assert((flags & GLOB_ERR) == GLOB_ERR);
49         assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
50
51         hFind = FindFirstFileW(pattern, &dat);
52         if (hFind == INVALID_HANDLE_VALUE) {
53                 err = GetLastError();
54                 if (err == ERROR_FILE_NOT_FOUND) {
55                         errno = 0;
56                         return GLOB_NOMATCH;
57                 } else {
58                         /* The other possible error codes for FindFirstFile()
59                          * are undocumented. */
60                         errno = EIO;
61                         return GLOB_ABORTED;
62                 }
63         }
64         pglob->gl_pathc = 0;
65         pglob->gl_pathv = NULL;
66         nspaces = 0;
67         do {
68                 wchar_t *path;
69                 if (pglob->gl_pathc == nspaces) {
70                         size_t new_nspaces;
71                         wchar_t **pathv;
72
73                         new_nspaces = nspaces * 2 + 1;  
74                         pathv = realloc(pglob->gl_pathv,
75                                         new_nspaces * sizeof(pglob->gl_pathv[0]));
76                         if (!pathv)
77                                 goto oom;
78                         pglob->gl_pathv = pathv;
79                         nspaces = new_nspaces;
80                 }
81                 size_t filename_len = wcslen(dat.cFileName);
82                 size_t len_needed = prefix_len + filename_len;
83
84                 path = malloc((len_needed + 1) * sizeof(wchar_t));
85                 if (!path)
86                         goto oom;
87
88                 wmemcpy(path, pattern, prefix_len);
89                 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
90                 pglob->gl_pathv[pglob->gl_pathc++] = path;
91         } while (FindNextFileW(hFind, &dat));
92         err = GetLastError();
93         CloseHandle(hFind);
94         if (err == ERROR_NO_MORE_FILES) {
95                 errno = 0;
96                 return 0;
97         } else {
98                 /* Other possible error codes for FindNextFile() are
99                  * undocumented */
100                 errno = EIO;
101                 ret = GLOB_ABORTED;
102                 goto fail_globfree;
103         }
104 oom:
105         CloseHandle(hFind);
106         errno = ENOMEM;
107         ret = GLOB_NOSPACE;
108 fail_globfree:
109         globfree(pglob);
110         return ret;
111 }
112
113 void
114 globfree(glob_t *pglob)
115 {
116         size_t i;
117         for (i = 0; i < pglob->gl_pathc; i++)
118                 free(pglob->gl_pathv[i]);
119         free(pglob->gl_pathv);
120 }
121
122 static bool
123 win32_modify_privilege(const wchar_t *privilege, bool enable)
124 {
125         HANDLE hToken;
126         LUID luid;
127         TOKEN_PRIVILEGES newState;
128         bool ret = false;
129
130         if (!OpenProcessToken(GetCurrentProcess(),
131                               TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
132                               &hToken))
133                 goto out;
134
135         if (!LookupPrivilegeValueW(NULL, privilege, &luid))
136                 goto out;
137
138         newState.PrivilegeCount = 1;
139         newState.Privileges[0].Luid = luid;
140         newState.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0);
141         ret = AdjustTokenPrivileges(hToken, FALSE, &newState, 0, NULL, NULL);
142         CloseHandle(hToken);
143 out:
144         if (!ret) {
145                 fwprintf(stderr, L"WARNING: Failed to %ls privilege %s\n",
146                         enable ? L"enable" : L"disable", privilege);
147                 fwprintf(stderr,
148                         L"WARNING: The program will continue, "
149                         L"but if permission issues are\n"
150                         L"encountered, you may need to run "
151                         L"this program as the administrator\n");
152         }
153         return ret;
154 }
155
156 static void
157 win32_modify_capture_privileges(bool enable)
158 {
159         win32_modify_privilege(SE_BACKUP_NAME, enable);
160         win32_modify_privilege(SE_SECURITY_NAME, enable);
161 }
162
163 static void
164 win32_modify_restore_privileges(bool enable)
165 {
166         win32_modify_privilege(SE_RESTORE_NAME, enable);
167         win32_modify_privilege(SE_SECURITY_NAME, enable);
168         win32_modify_privilege(SE_TAKE_OWNERSHIP_NAME, enable);
169 }
170
171 void
172 win32_acquire_capture_privileges(void)
173 {
174         win32_modify_capture_privileges(true);
175 }
176
177 void
178 win32_release_capture_privileges(void)
179 {
180         win32_modify_capture_privileges(false);
181 }
182
183 void
184 win32_acquire_restore_privileges(void)
185 {
186         win32_modify_restore_privileges(true);
187 }
188
189 void
190 win32_release_restore_privileges(void)
191 {
192         win32_modify_restore_privileges(false);
193 }
194
195 /* Convert a string from the "current Windows codepage" to UTF-16LE. */
196 wchar_t *
197 win32_mbs_to_wcs(const char *mbs, size_t mbs_nbytes, size_t *num_wchars_ret)
198 {
199         if (mbs_nbytes > INT_MAX) {
200                 fwprintf(stderr, L"ERROR: too much data (%zu bytes)!\n",
201                          mbs_nbytes);
202                 return NULL;
203         }
204         if (mbs_nbytes == 0) {
205                 *num_wchars_ret = 0;
206                 return (wchar_t*)mbs;
207         }
208         int len = MultiByteToWideChar(CP_ACP,
209                                       MB_ERR_INVALID_CHARS,
210                                       mbs,
211                                       mbs_nbytes,
212                                       NULL,
213                                       0);
214         if (len <= 0)
215                 goto out_invalid;
216         wchar_t *wcs = malloc(len * sizeof(wchar_t));
217         if (!wcs) {
218                 fwprintf(stderr, L"ERROR: out of memory!\n");
219                 return NULL;
220         }
221         int len2 = MultiByteToWideChar(CP_ACP,
222                                        MB_ERR_INVALID_CHARS,
223                                        mbs,
224                                        mbs_nbytes,
225                                        wcs,
226                                        len);
227         if (len2 != len) {
228                 free(wcs);
229                 goto out_invalid;
230         }
231         *num_wchars_ret = len;
232         return wcs;
233 out_invalid:
234         fwprintf(stderr,
235 L"ERROR: Invalid multi-byte string in the text file you provided as input!\n"
236 L"       Maybe try converting your text file to UTF-16LE?\n"
237         );
238         return NULL;
239 }
240
241 static inline bool
242 is_path_separator(wchar_t c)
243 {
244         return c == L'/' || c == L'\\';
245 }
246
247 /* basename() (modifying, trailing-slash stripping version) for wide-character
248  * strings. */
249 wchar_t *
250 win32_wbasename(wchar_t *path)
251 {
252         wchar_t *p = wcschr(path, L'\0');
253
254         p--;
255         while (p >= path && is_path_separator(*p))
256                 *p-- = '\0';
257         while (p >= path && !is_path_separator(*p))
258                 p--;
259         p++;
260         return p;
261 }
262