blob: 84574032e6892ad0f09bf7989be412cb9e47bc33 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/win32filesystem.h"
12
13#include "webrtc/base/win32.h"
14#include <shellapi.h>
15#include <shlobj.h>
16#include <tchar.h>
17
jbauch555604a2016-04-26 03:13:22 -070018#include <memory>
19
tfarina5237aaf2015-11-10 23:44:30 -080020#include "webrtc/base/arraysize.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include "webrtc/base/fileutils.h"
22#include "webrtc/base/pathutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#include "webrtc/base/stream.h"
24#include "webrtc/base/stringutils.h"
25
26// In several places in this file, we test the integrity level of the process
27// before calling GetLongPathName. We do this because calling GetLongPathName
28// when running under protected mode IE (a low integrity process) can result in
29// a virtualized path being returned, which is wrong if you only plan to read.
30// TODO: Waiting to hear back from IE team on whether this is the
31// best approach; IEIsProtectedModeProcess is another possible solution.
32
33namespace rtc {
34
35bool Win32Filesystem::CreateFolder(const Pathname &pathname) {
36 if (pathname.pathname().empty() || !pathname.filename().empty())
37 return false;
38
39 std::wstring path16;
40 if (!Utf8ToWindowsFilename(pathname.pathname(), &path16))
41 return false;
42
43 DWORD res = ::GetFileAttributes(path16.c_str());
44 if (res != INVALID_FILE_ATTRIBUTES) {
45 // Something exists at this location, check if it is a directory
46 return ((res & FILE_ATTRIBUTE_DIRECTORY) != 0);
47 } else if ((GetLastError() != ERROR_FILE_NOT_FOUND)
48 && (GetLastError() != ERROR_PATH_NOT_FOUND)) {
49 // Unexpected error
50 return false;
51 }
52
53 // Directory doesn't exist, look up one directory level
54 if (!pathname.parent_folder().empty()) {
55 Pathname parent(pathname);
56 parent.SetFolder(pathname.parent_folder());
57 if (!CreateFolder(parent)) {
58 return false;
59 }
60 }
61
62 return (::CreateDirectory(path16.c_str(), NULL) != 0);
63}
64
65FileStream *Win32Filesystem::OpenFile(const Pathname &filename,
66 const std::string &mode) {
67 FileStream *fs = new FileStream();
68 if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
69 delete fs;
70 fs = NULL;
71 }
72 return fs;
73}
74
75bool Win32Filesystem::CreatePrivateFile(const Pathname &filename) {
76 // To make the file private to the current user, we first must construct a
77 // SECURITY_DESCRIPTOR specifying an ACL. This code is mostly based upon
78 // http://msdn.microsoft.com/en-us/library/ms707085%28VS.85%29.aspx
79
80 // Get the current process token.
81 HANDLE process_token = INVALID_HANDLE_VALUE;
82 if (!::OpenProcessToken(::GetCurrentProcess(),
83 TOKEN_QUERY,
84 &process_token)) {
85 LOG_ERR(LS_ERROR) << "OpenProcessToken() failed";
86 return false;
87 }
88
89 // Get the size of its TOKEN_USER structure. Return value is not checked
90 // because we expect it to fail.
91 DWORD token_user_size = 0;
92 (void)::GetTokenInformation(process_token,
93 TokenUser,
94 NULL,
95 0,
96 &token_user_size);
97
98 // Get the TOKEN_USER structure.
jbauch555604a2016-04-26 03:13:22 -070099 std::unique_ptr<char[]> token_user_bytes(new char[token_user_size]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000100 PTOKEN_USER token_user = reinterpret_cast<PTOKEN_USER>(
101 token_user_bytes.get());
102 memset(token_user, 0, token_user_size);
103 BOOL success = ::GetTokenInformation(process_token,
104 TokenUser,
105 token_user,
106 token_user_size,
107 &token_user_size);
108 // We're now done with this.
109 ::CloseHandle(process_token);
110 if (!success) {
111 LOG_ERR(LS_ERROR) << "GetTokenInformation() failed";
112 return false;
113 }
114
115 if (!IsValidSid(token_user->User.Sid)) {
116 LOG_ERR(LS_ERROR) << "Current process has invalid user SID";
117 return false;
118 }
119
120 // Compute size needed for an ACL that allows access to just this user.
121 int acl_size = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) +
122 GetLengthSid(token_user->User.Sid);
123
124 // Allocate it.
jbauch555604a2016-04-26 03:13:22 -0700125 std::unique_ptr<char[]> acl_bytes(new char[acl_size]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 PACL acl = reinterpret_cast<PACL>(acl_bytes.get());
127 memset(acl, 0, acl_size);
128 if (!::InitializeAcl(acl, acl_size, ACL_REVISION)) {
129 LOG_ERR(LS_ERROR) << "InitializeAcl() failed";
130 return false;
131 }
132
133 // Allow access to only the current user.
134 if (!::AddAccessAllowedAce(acl,
135 ACL_REVISION,
136 GENERIC_READ | GENERIC_WRITE | STANDARD_RIGHTS_ALL,
137 token_user->User.Sid)) {
138 LOG_ERR(LS_ERROR) << "AddAccessAllowedAce() failed";
139 return false;
140 }
141
142 // Now make the security descriptor.
143 SECURITY_DESCRIPTOR security_descriptor;
144 if (!::InitializeSecurityDescriptor(&security_descriptor,
145 SECURITY_DESCRIPTOR_REVISION)) {
146 LOG_ERR(LS_ERROR) << "InitializeSecurityDescriptor() failed";
147 return false;
148 }
149
150 // Put the ACL in it.
151 if (!::SetSecurityDescriptorDacl(&security_descriptor,
152 TRUE,
153 acl,
154 FALSE)) {
155 LOG_ERR(LS_ERROR) << "SetSecurityDescriptorDacl() failed";
156 return false;
157 }
158
159 // Finally create the file.
160 SECURITY_ATTRIBUTES security_attributes;
161 security_attributes.nLength = sizeof(security_attributes);
162 security_attributes.lpSecurityDescriptor = &security_descriptor;
163 security_attributes.bInheritHandle = FALSE;
164 HANDLE handle = ::CreateFile(
165 ToUtf16(filename.pathname()).c_str(),
166 GENERIC_READ | GENERIC_WRITE,
167 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
168 &security_attributes,
169 CREATE_NEW,
170 0,
171 NULL);
172 if (INVALID_HANDLE_VALUE == handle) {
173 LOG_ERR(LS_ERROR) << "CreateFile() failed";
174 return false;
175 }
176 if (!::CloseHandle(handle)) {
177 LOG_ERR(LS_ERROR) << "CloseFile() failed";
178 // Continue.
179 }
180 return true;
181}
182
183bool Win32Filesystem::DeleteFile(const Pathname &filename) {
184 LOG(LS_INFO) << "Deleting file " << filename.pathname();
185 if (!IsFile(filename)) {
186 ASSERT(IsFile(filename));
187 return false;
188 }
189 return ::DeleteFile(ToUtf16(filename.pathname()).c_str()) != 0;
190}
191
192bool Win32Filesystem::DeleteEmptyFolder(const Pathname &folder) {
193 LOG(LS_INFO) << "Deleting folder " << folder.pathname();
194
195 std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
196 return ::RemoveDirectory(ToUtf16(no_slash).c_str()) != 0;
197}
198
199bool Win32Filesystem::GetTemporaryFolder(Pathname &pathname, bool create,
200 const std::string *append) {
201 wchar_t buffer[MAX_PATH + 1];
tfarina5237aaf2015-11-10 23:44:30 -0800202 if (!::GetTempPath(arraysize(buffer), buffer))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203 return false;
204 if (!IsCurrentProcessLowIntegrity() &&
tfarina5237aaf2015-11-10 23:44:30 -0800205 !::GetLongPathName(buffer, buffer, arraysize(buffer)))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000206 return false;
207 size_t len = strlen(buffer);
208 if ((len > 0) && (buffer[len-1] != '\\')) {
tfarina5237aaf2015-11-10 23:44:30 -0800209 len += strcpyn(buffer + len, arraysize(buffer) - len, L"\\");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 }
tfarina5237aaf2015-11-10 23:44:30 -0800211 if (len >= arraysize(buffer) - 1)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212 return false;
213 pathname.clear();
214 pathname.SetFolder(ToUtf8(buffer));
215 if (append != NULL) {
216 ASSERT(!append->empty());
217 pathname.AppendFolder(*append);
218 }
219 return !create || CreateFolder(pathname);
220}
221
222std::string Win32Filesystem::TempFilename(const Pathname &dir,
223 const std::string &prefix) {
224 wchar_t filename[MAX_PATH];
225 if (::GetTempFileName(ToUtf16(dir.pathname()).c_str(),
226 ToUtf16(prefix).c_str(), 0, filename) != 0)
227 return ToUtf8(filename);
228 ASSERT(false);
229 return "";
230}
231
232bool Win32Filesystem::MoveFile(const Pathname &old_path,
233 const Pathname &new_path) {
234 if (!IsFile(old_path)) {
235 ASSERT(IsFile(old_path));
236 return false;
237 }
238 LOG(LS_INFO) << "Moving " << old_path.pathname()
239 << " to " << new_path.pathname();
240 return ::MoveFile(ToUtf16(old_path.pathname()).c_str(),
241 ToUtf16(new_path.pathname()).c_str()) != 0;
242}
243
244bool Win32Filesystem::MoveFolder(const Pathname &old_path,
245 const Pathname &new_path) {
246 if (!IsFolder(old_path)) {
247 ASSERT(IsFolder(old_path));
248 return false;
249 }
250 LOG(LS_INFO) << "Moving " << old_path.pathname()
251 << " to " << new_path.pathname();
252 if (::MoveFile(ToUtf16(old_path.pathname()).c_str(),
253 ToUtf16(new_path.pathname()).c_str()) == 0) {
254 if (::GetLastError() != ERROR_NOT_SAME_DEVICE) {
255 LOG_GLE(LS_ERROR) << "Failed to move file";
256 return false;
257 }
258 if (!CopyFolder(old_path, new_path))
259 return false;
260 if (!DeleteFolderAndContents(old_path))
261 return false;
262 }
263 return true;
264}
265
266bool Win32Filesystem::IsFolder(const Pathname &path) {
267 WIN32_FILE_ATTRIBUTE_DATA data = {0};
268 if (0 == ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
269 GetFileExInfoStandard, &data))
270 return false;
271 return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
272 FILE_ATTRIBUTE_DIRECTORY;
273}
274
275bool Win32Filesystem::IsFile(const Pathname &path) {
276 WIN32_FILE_ATTRIBUTE_DATA data = {0};
277 if (0 == ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
278 GetFileExInfoStandard, &data))
279 return false;
280 return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
281}
282
283bool Win32Filesystem::IsAbsent(const Pathname& path) {
284 WIN32_FILE_ATTRIBUTE_DATA data = {0};
285 if (0 != ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
286 GetFileExInfoStandard, &data))
287 return false;
288 DWORD err = ::GetLastError();
289 return (ERROR_FILE_NOT_FOUND == err || ERROR_PATH_NOT_FOUND == err);
290}
291
292bool Win32Filesystem::CopyFile(const Pathname &old_path,
293 const Pathname &new_path) {
294 return ::CopyFile(ToUtf16(old_path.pathname()).c_str(),
295 ToUtf16(new_path.pathname()).c_str(), TRUE) != 0;
296}
297
298bool Win32Filesystem::IsTemporaryPath(const Pathname& pathname) {
299 TCHAR buffer[MAX_PATH + 1];
tfarina5237aaf2015-11-10 23:44:30 -0800300 if (!::GetTempPath(arraysize(buffer), buffer))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301 return false;
302 if (!IsCurrentProcessLowIntegrity() &&
tfarina5237aaf2015-11-10 23:44:30 -0800303 !::GetLongPathName(buffer, buffer, arraysize(buffer)))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304 return false;
305 return (::strnicmp(ToUtf16(pathname.pathname()).c_str(),
306 buffer, strlen(buffer)) == 0);
307}
308
309bool Win32Filesystem::GetFileSize(const Pathname &pathname, size_t *size) {
310 WIN32_FILE_ATTRIBUTE_DATA data = {0};
311 if (::GetFileAttributesEx(ToUtf16(pathname.pathname()).c_str(),
312 GetFileExInfoStandard, &data) == 0)
313 return false;
314 *size = data.nFileSizeLow;
315 return true;
316}
317
318bool Win32Filesystem::GetFileTime(const Pathname& path, FileTimeType which,
319 time_t* time) {
320 WIN32_FILE_ATTRIBUTE_DATA data = {0};
321 if (::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
322 GetFileExInfoStandard, &data) == 0)
323 return false;
324 switch (which) {
325 case FTT_CREATED:
326 FileTimeToUnixTime(data.ftCreationTime, time);
327 break;
328 case FTT_MODIFIED:
329 FileTimeToUnixTime(data.ftLastWriteTime, time);
330 break;
331 case FTT_ACCESSED:
332 FileTimeToUnixTime(data.ftLastAccessTime, time);
333 break;
334 default:
335 return false;
336 }
337 return true;
338}
339
340bool Win32Filesystem::GetAppPathname(Pathname* path) {
341 TCHAR buffer[MAX_PATH + 1];
tfarina5237aaf2015-11-10 23:44:30 -0800342 if (0 == ::GetModuleFileName(NULL, buffer, arraysize(buffer)))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343 return false;
344 path->SetPathname(ToUtf8(buffer));
345 return true;
346}
347
348bool Win32Filesystem::GetAppDataFolder(Pathname* path, bool per_user) {
349 ASSERT(!organization_name_.empty());
350 ASSERT(!application_name_.empty());
351 TCHAR buffer[MAX_PATH + 1];
352 int csidl = per_user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA;
353 if (!::SHGetSpecialFolderPath(NULL, buffer, csidl, TRUE))
354 return false;
355 if (!IsCurrentProcessLowIntegrity() &&
tfarina5237aaf2015-11-10 23:44:30 -0800356 !::GetLongPathName(buffer, buffer, arraysize(buffer)))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357 return false;
tfarina5237aaf2015-11-10 23:44:30 -0800358 size_t len = strcatn(buffer, arraysize(buffer), __T("\\"));
359 len += strcpyn(buffer + len, arraysize(buffer) - len,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360 ToUtf16(organization_name_).c_str());
361 if ((len > 0) && (buffer[len-1] != __T('\\'))) {
tfarina5237aaf2015-11-10 23:44:30 -0800362 len += strcpyn(buffer + len, arraysize(buffer) - len, __T("\\"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363 }
tfarina5237aaf2015-11-10 23:44:30 -0800364 len += strcpyn(buffer + len, arraysize(buffer) - len,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365 ToUtf16(application_name_).c_str());
366 if ((len > 0) && (buffer[len-1] != __T('\\'))) {
tfarina5237aaf2015-11-10 23:44:30 -0800367 len += strcpyn(buffer + len, arraysize(buffer) - len, __T("\\"));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368 }
tfarina5237aaf2015-11-10 23:44:30 -0800369 if (len >= arraysize(buffer) - 1)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 return false;
371 path->clear();
372 path->SetFolder(ToUtf8(buffer));
373 return CreateFolder(*path);
374}
375
376bool Win32Filesystem::GetAppTempFolder(Pathname* path) {
377 if (!GetAppPathname(path))
378 return false;
379 std::string filename(path->filename());
380 return GetTemporaryFolder(*path, true, &filename);
381}
382
jlmiller@webrtc.orgea1c8422015-01-22 17:44:19 +0000383bool Win32Filesystem::GetDiskFreeSpace(const Pathname& path,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200384 int64_t* free_bytes) {
jlmiller@webrtc.orgea1c8422015-01-22 17:44:19 +0000385 if (!free_bytes) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386 return false;
387 }
388 char drive[4];
389 std::wstring drive16;
390 const wchar_t* target_drive = NULL;
391 if (path.GetDrive(drive, sizeof(drive))) {
392 drive16 = ToUtf16(drive);
393 target_drive = drive16.c_str();
394 } else if (path.folder().substr(0, 2) == "\\\\") {
395 // UNC path, fail.
396 // TODO: Handle UNC paths.
397 return false;
398 } else {
399 // The path is probably relative. GetDriveType and GetDiskFreeSpaceEx
400 // use the current drive if NULL is passed as the drive name.
401 // TODO: Add method to Pathname to determine if the path is relative.
402 // TODO: Add method to Pathname to convert a path to absolute.
403 }
jlmiller@webrtc.orgea1c8422015-01-22 17:44:19 +0000404 UINT drive_type = ::GetDriveType(target_drive);
405 if ((drive_type == DRIVE_REMOTE) || (drive_type == DRIVE_UNKNOWN)) {
406 LOG(LS_VERBOSE) << "Remote or unknown drive: " << drive;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407 return false;
408 }
409
Peter Boström0c4e06b2015-10-07 12:23:21 +0200410 int64_t total_number_of_bytes; // receives the number of bytes on disk
411 int64_t total_number_of_free_bytes; // receives the free bytes on disk
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 // make sure things won't change in 64 bit machine
413 // TODO replace with compile time assert
Peter Boström0c4e06b2015-10-07 12:23:21 +0200414 ASSERT(sizeof(ULARGE_INTEGER) == sizeof(uint64_t)); // NOLINT
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 if (::GetDiskFreeSpaceEx(target_drive,
jlmiller@webrtc.orgea1c8422015-01-22 17:44:19 +0000416 (PULARGE_INTEGER)free_bytes,
417 (PULARGE_INTEGER)&total_number_of_bytes,
418 (PULARGE_INTEGER)&total_number_of_free_bytes)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000419 return true;
420 } else {
jlmiller@webrtc.orgea1c8422015-01-22 17:44:19 +0000421 LOG(LS_VERBOSE) << "GetDiskFreeSpaceEx returns error.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422 return false;
423 }
424}
425
426Pathname Win32Filesystem::GetCurrentDirectory() {
427 Pathname cwd;
428 int path_len = 0;
jbauch555604a2016-04-26 03:13:22 -0700429 std::unique_ptr<wchar_t[]> path;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000430 do {
431 int needed = ::GetCurrentDirectory(path_len, path.get());
432 if (needed == 0) {
433 // Error.
434 LOG_GLE(LS_ERROR) << "::GetCurrentDirectory() failed";
435 return cwd; // returns empty pathname
436 }
437 if (needed <= path_len) {
438 // It wrote successfully.
439 break;
440 }
441 // Else need to re-alloc for "needed".
442 path.reset(new wchar_t[needed]);
443 path_len = needed;
444 } while (true);
445 cwd.SetFolder(ToUtf8(path.get()));
446 return cwd;
447}
448
449// TODO: Consider overriding DeleteFolderAndContents for speed and potentially
450// better OS integration (recycle bin?)
451/*
452 std::wstring temp_path16 = ToUtf16(temp_path.pathname());
453 temp_path16.append(1, '*');
454 temp_path16.append(1, '\0');
455
456 SHFILEOPSTRUCT file_op = { 0 };
457 file_op.wFunc = FO_DELETE;
458 file_op.pFrom = temp_path16.c_str();
459 file_op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
460 return (0 == SHFileOperation(&file_op));
461*/
462
463} // namespace rtc