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