You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

477 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2006, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/base/win32filesystem.h"
  28. #include "talk/base/win32.h"
  29. #include <shellapi.h>
  30. #include <shlobj.h>
  31. #include <tchar.h>
  32. #include "talk/base/fileutils.h"
  33. #include "talk/base/pathutils.h"
  34. #include "talk/base/scoped_ptr.h"
  35. #include "talk/base/stream.h"
  36. #include "talk/base/stringutils.h"
  37. // In several places in this file, we test the integrity level of the process
  38. // before calling GetLongPathName. We do this because calling GetLongPathName
  39. // when running under protected mode IE (a low integrity process) can result in
  40. // a virtualized path being returned, which is wrong if you only plan to read.
  41. // TODO: Waiting to hear back from IE team on whether this is the
  42. // best approach; IEIsProtectedModeProcess is another possible solution.
  43. namespace talk_base {
  44. bool Win32Filesystem::CreateFolder(const Pathname &pathname) {
  45. if (pathname.pathname().empty() || !pathname.filename().empty())
  46. return false;
  47. std::wstring path16;
  48. if (!Utf8ToWindowsFilename(pathname.pathname(), &path16))
  49. return false;
  50. DWORD res = ::GetFileAttributes(path16.c_str());
  51. if (res != INVALID_FILE_ATTRIBUTES) {
  52. // Something exists at this location, check if it is a directory
  53. return ((res & FILE_ATTRIBUTE_DIRECTORY) != 0);
  54. } else if ((GetLastError() != ERROR_FILE_NOT_FOUND)
  55. && (GetLastError() != ERROR_PATH_NOT_FOUND)) {
  56. // Unexpected error
  57. return false;
  58. }
  59. // Directory doesn't exist, look up one directory level
  60. if (!pathname.parent_folder().empty()) {
  61. Pathname parent(pathname);
  62. parent.SetFolder(pathname.parent_folder());
  63. if (!CreateFolder(parent)) {
  64. return false;
  65. }
  66. }
  67. return (::CreateDirectory(path16.c_str(), NULL) != 0);
  68. }
  69. FileStream *Win32Filesystem::OpenFile(const Pathname &filename,
  70. const std::string &mode) {
  71. FileStream *fs = new FileStream();
  72. if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
  73. delete fs;
  74. fs = NULL;
  75. }
  76. return fs;
  77. }
  78. bool Win32Filesystem::CreatePrivateFile(const Pathname &filename) {
  79. // To make the file private to the current user, we first must construct a
  80. // SECURITY_DESCRIPTOR specifying an ACL. This code is mostly based upon
  81. // http://msdn.microsoft.com/en-us/library/ms707085%28VS.85%29.aspx
  82. // Get the current process token.
  83. HANDLE process_token = INVALID_HANDLE_VALUE;
  84. if (!::OpenProcessToken(::GetCurrentProcess(),
  85. TOKEN_QUERY,
  86. &process_token)) {
  87. LOG_ERR(LS_ERROR) << "OpenProcessToken() failed";
  88. return false;
  89. }
  90. // Get the size of its TOKEN_USER structure. Return value is not checked
  91. // because we expect it to fail.
  92. DWORD token_user_size = 0;
  93. (void)::GetTokenInformation(process_token,
  94. TokenUser,
  95. NULL,
  96. 0,
  97. &token_user_size);
  98. // Get the TOKEN_USER structure.
  99. scoped_array<char> token_user_bytes(new char[token_user_size]);
  100. 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. if (!IsValidSid(token_user->User.Sid)) {
  115. LOG_ERR(LS_ERROR) << "Current process has invalid user SID";
  116. return false;
  117. }
  118. // Compute size needed for an ACL that allows access to just this user.
  119. int acl_size = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) +
  120. GetLengthSid(token_user->User.Sid);
  121. // Allocate it.
  122. scoped_array<char> acl_bytes(new char[acl_size]);
  123. PACL acl = reinterpret_cast<PACL>(acl_bytes.get());
  124. memset(acl, 0, acl_size);
  125. if (!::InitializeAcl(acl, acl_size, ACL_REVISION)) {
  126. LOG_ERR(LS_ERROR) << "InitializeAcl() failed";
  127. return false;
  128. }
  129. // Allow access to only the current user.
  130. if (!::AddAccessAllowedAce(acl,
  131. ACL_REVISION,
  132. GENERIC_READ | GENERIC_WRITE | STANDARD_RIGHTS_ALL,
  133. token_user->User.Sid)) {
  134. LOG_ERR(LS_ERROR) << "AddAccessAllowedAce() failed";
  135. return false;
  136. }
  137. // Now make the security descriptor.
  138. SECURITY_DESCRIPTOR security_descriptor;
  139. if (!::InitializeSecurityDescriptor(&security_descriptor,
  140. SECURITY_DESCRIPTOR_REVISION)) {
  141. LOG_ERR(LS_ERROR) << "InitializeSecurityDescriptor() failed";
  142. return false;
  143. }
  144. // Put the ACL in it.
  145. if (!::SetSecurityDescriptorDacl(&security_descriptor,
  146. TRUE,
  147. acl,
  148. FALSE)) {
  149. LOG_ERR(LS_ERROR) << "SetSecurityDescriptorDacl() failed";
  150. return false;
  151. }
  152. // Finally create the file.
  153. SECURITY_ATTRIBUTES security_attributes;
  154. security_attributes.nLength = sizeof(security_attributes);
  155. security_attributes.lpSecurityDescriptor = &security_descriptor;
  156. security_attributes.bInheritHandle = FALSE;
  157. HANDLE handle = ::CreateFile(
  158. ToUtf16(filename.pathname()).c_str(),
  159. GENERIC_READ | GENERIC_WRITE,
  160. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  161. &security_attributes,
  162. CREATE_NEW,
  163. 0,
  164. NULL);
  165. if (INVALID_HANDLE_VALUE == handle) {
  166. LOG_ERR(LS_ERROR) << "CreateFile() failed";
  167. return false;
  168. }
  169. if (!::CloseHandle(handle)) {
  170. LOG_ERR(LS_ERROR) << "CloseFile() failed";
  171. // Continue.
  172. }
  173. return true;
  174. }
  175. bool Win32Filesystem::DeleteFile(const Pathname &filename) {
  176. LOG(LS_INFO) << "Deleting file " << filename.pathname();
  177. if (!IsFile(filename)) {
  178. ASSERT(IsFile(filename));
  179. return false;
  180. }
  181. return ::DeleteFile(ToUtf16(filename.pathname()).c_str()) != 0;
  182. }
  183. bool Win32Filesystem::DeleteEmptyFolder(const Pathname &folder) {
  184. LOG(LS_INFO) << "Deleting folder " << folder.pathname();
  185. std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
  186. return ::RemoveDirectory(ToUtf16(no_slash).c_str()) != 0;
  187. }
  188. bool Win32Filesystem::GetTemporaryFolder(Pathname &pathname, bool create,
  189. const std::string *append) {
  190. wchar_t buffer[MAX_PATH + 1];
  191. if (!::GetTempPath(ARRAY_SIZE(buffer), buffer))
  192. return false;
  193. if (!IsCurrentProcessLowIntegrity() &&
  194. !::GetLongPathName(buffer, buffer, ARRAY_SIZE(buffer)))
  195. return false;
  196. size_t len = strlen(buffer);
  197. if ((len > 0) && (buffer[len-1] != '\\')) {
  198. len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len, L"\\");
  199. }
  200. if (len >= ARRAY_SIZE(buffer) - 1)
  201. return false;
  202. pathname.clear();
  203. pathname.SetFolder(ToUtf8(buffer));
  204. if (append != NULL) {
  205. ASSERT(!append->empty());
  206. pathname.AppendFolder(*append);
  207. }
  208. return !create || CreateFolder(pathname);
  209. }
  210. std::string Win32Filesystem::TempFilename(const Pathname &dir,
  211. const std::string &prefix) {
  212. wchar_t filename[MAX_PATH];
  213. if (::GetTempFileName(ToUtf16(dir.pathname()).c_str(),
  214. ToUtf16(prefix).c_str(), 0, filename) != 0)
  215. return ToUtf8(filename);
  216. ASSERT(false);
  217. return "";
  218. }
  219. bool Win32Filesystem::MoveFile(const Pathname &old_path,
  220. const Pathname &new_path) {
  221. if (!IsFile(old_path)) {
  222. ASSERT(IsFile(old_path));
  223. return false;
  224. }
  225. LOG(LS_INFO) << "Moving " << old_path.pathname()
  226. << " to " << new_path.pathname();
  227. return ::MoveFile(ToUtf16(old_path.pathname()).c_str(),
  228. ToUtf16(new_path.pathname()).c_str()) != 0;
  229. }
  230. bool Win32Filesystem::MoveFolder(const Pathname &old_path,
  231. const Pathname &new_path) {
  232. if (!IsFolder(old_path)) {
  233. ASSERT(IsFolder(old_path));
  234. return false;
  235. }
  236. LOG(LS_INFO) << "Moving " << old_path.pathname()
  237. << " to " << new_path.pathname();
  238. if (::MoveFile(ToUtf16(old_path.pathname()).c_str(),
  239. ToUtf16(new_path.pathname()).c_str()) == 0) {
  240. if (::GetLastError() != ERROR_NOT_SAME_DEVICE) {
  241. LOG_GLE(LS_ERROR) << "Failed to move file";
  242. return false;
  243. }
  244. if (!CopyFolder(old_path, new_path))
  245. return false;
  246. if (!DeleteFolderAndContents(old_path))
  247. return false;
  248. }
  249. return true;
  250. }
  251. bool Win32Filesystem::IsFolder(const Pathname &path) {
  252. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  253. if (0 == ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
  254. GetFileExInfoStandard, &data))
  255. return false;
  256. return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
  257. FILE_ATTRIBUTE_DIRECTORY;
  258. }
  259. bool Win32Filesystem::IsFile(const Pathname &path) {
  260. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  261. if (0 == ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
  262. GetFileExInfoStandard, &data))
  263. return false;
  264. return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
  265. }
  266. bool Win32Filesystem::IsAbsent(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. DWORD err = ::GetLastError();
  272. return (ERROR_FILE_NOT_FOUND == err || ERROR_PATH_NOT_FOUND == err);
  273. }
  274. bool Win32Filesystem::CopyFile(const Pathname &old_path,
  275. const Pathname &new_path) {
  276. return ::CopyFile(ToUtf16(old_path.pathname()).c_str(),
  277. ToUtf16(new_path.pathname()).c_str(), TRUE) != 0;
  278. }
  279. bool Win32Filesystem::IsTemporaryPath(const Pathname& pathname) {
  280. TCHAR buffer[MAX_PATH + 1];
  281. if (!::GetTempPath(ARRAY_SIZE(buffer), buffer))
  282. return false;
  283. if (!IsCurrentProcessLowIntegrity() &&
  284. !::GetLongPathName(buffer, buffer, ARRAY_SIZE(buffer)))
  285. return false;
  286. return (::strnicmp(ToUtf16(pathname.pathname()).c_str(),
  287. buffer, strlen(buffer)) == 0);
  288. }
  289. bool Win32Filesystem::GetFileSize(const Pathname &pathname, size_t *size) {
  290. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  291. if (::GetFileAttributesEx(ToUtf16(pathname.pathname()).c_str(),
  292. GetFileExInfoStandard, &data) == 0)
  293. return false;
  294. *size = data.nFileSizeLow;
  295. return true;
  296. }
  297. bool Win32Filesystem::GetFileTime(const Pathname& path, FileTimeType which,
  298. time_t* time) {
  299. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  300. if (::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
  301. GetFileExInfoStandard, &data) == 0)
  302. return false;
  303. switch (which) {
  304. case FTT_CREATED:
  305. FileTimeToUnixTime(data.ftCreationTime, time);
  306. break;
  307. case FTT_MODIFIED:
  308. FileTimeToUnixTime(data.ftLastWriteTime, time);
  309. break;
  310. case FTT_ACCESSED:
  311. FileTimeToUnixTime(data.ftLastAccessTime, time);
  312. break;
  313. default:
  314. return false;
  315. }
  316. return true;
  317. }
  318. bool Win32Filesystem::GetAppPathname(Pathname* path) {
  319. TCHAR buffer[MAX_PATH + 1];
  320. if (0 == ::GetModuleFileName(NULL, buffer, ARRAY_SIZE(buffer)))
  321. return false;
  322. path->SetPathname(ToUtf8(buffer));
  323. return true;
  324. }
  325. bool Win32Filesystem::GetAppDataFolder(Pathname* path, bool per_user) {
  326. ASSERT(!organization_name_.empty());
  327. ASSERT(!application_name_.empty());
  328. TCHAR buffer[MAX_PATH + 1];
  329. int csidl = per_user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA;
  330. if (!::SHGetSpecialFolderPath(NULL, buffer, csidl, TRUE))
  331. return false;
  332. if (!IsCurrentProcessLowIntegrity() &&
  333. !::GetLongPathName(buffer, buffer, ARRAY_SIZE(buffer)))
  334. return false;
  335. size_t len = strcatn(buffer, ARRAY_SIZE(buffer), __T("\\"));
  336. len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len,
  337. ToUtf16(organization_name_).c_str());
  338. if ((len > 0) && (buffer[len-1] != __T('\\'))) {
  339. len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len, __T("\\"));
  340. }
  341. len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len,
  342. ToUtf16(application_name_).c_str());
  343. if ((len > 0) && (buffer[len-1] != __T('\\'))) {
  344. len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len, __T("\\"));
  345. }
  346. if (len >= ARRAY_SIZE(buffer) - 1)
  347. return false;
  348. path->clear();
  349. path->SetFolder(ToUtf8(buffer));
  350. return CreateFolder(*path);
  351. }
  352. bool Win32Filesystem::GetAppTempFolder(Pathname* path) {
  353. if (!GetAppPathname(path))
  354. return false;
  355. std::string filename(path->filename());
  356. return GetTemporaryFolder(*path, true, &filename);
  357. }
  358. bool Win32Filesystem::GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
  359. if (!freebytes) {
  360. return false;
  361. }
  362. char drive[4];
  363. std::wstring drive16;
  364. const wchar_t* target_drive = NULL;
  365. if (path.GetDrive(drive, sizeof(drive))) {
  366. drive16 = ToUtf16(drive);
  367. target_drive = drive16.c_str();
  368. } else if (path.folder().substr(0, 2) == "\\\\") {
  369. // UNC path, fail.
  370. // TODO: Handle UNC paths.
  371. return false;
  372. } else {
  373. // The path is probably relative. GetDriveType and GetDiskFreeSpaceEx
  374. // use the current drive if NULL is passed as the drive name.
  375. // TODO: Add method to Pathname to determine if the path is relative.
  376. // TODO: Add method to Pathname to convert a path to absolute.
  377. }
  378. UINT driveType = ::GetDriveType(target_drive);
  379. if ( (driveType & DRIVE_REMOTE) || (driveType & DRIVE_UNKNOWN) ) {
  380. LOG(LS_VERBOSE) << " remove or unknown drive " << drive;
  381. return false;
  382. }
  383. int64 totalNumberOfBytes; // receives the number of bytes on disk
  384. int64 totalNumberOfFreeBytes; // receives the free bytes on disk
  385. // make sure things won't change in 64 bit machine
  386. // TODO replace with compile time assert
  387. ASSERT(sizeof(ULARGE_INTEGER) == sizeof(uint64)); //NOLINT
  388. if (::GetDiskFreeSpaceEx(target_drive,
  389. (PULARGE_INTEGER)freebytes,
  390. (PULARGE_INTEGER)&totalNumberOfBytes,
  391. (PULARGE_INTEGER)&totalNumberOfFreeBytes)) {
  392. return true;
  393. } else {
  394. LOG(LS_VERBOSE) << " GetDiskFreeSpaceEx returns error ";
  395. return false;
  396. }
  397. }
  398. Pathname Win32Filesystem::GetCurrentDirectory() {
  399. Pathname cwd;
  400. int path_len = 0;
  401. scoped_array<wchar_t> path;
  402. do {
  403. int needed = ::GetCurrentDirectory(path_len, path.get());
  404. if (needed == 0) {
  405. // Error.
  406. LOG_GLE(LS_ERROR) << "::GetCurrentDirectory() failed";
  407. return cwd; // returns empty pathname
  408. }
  409. if (needed <= path_len) {
  410. // It wrote successfully.
  411. break;
  412. }
  413. // Else need to re-alloc for "needed".
  414. path.reset(new wchar_t[needed]);
  415. path_len = needed;
  416. } while (true);
  417. cwd.SetFolder(ToUtf8(path.get()));
  418. return cwd;
  419. }
  420. // TODO: Consider overriding DeleteFolderAndContents for speed and potentially
  421. // better OS integration (recycle bin?)
  422. /*
  423. std::wstring temp_path16 = ToUtf16(temp_path.pathname());
  424. temp_path16.append(1, '*');
  425. temp_path16.append(1, '\0');
  426. SHFILEOPSTRUCT file_op = { 0 };
  427. file_op.wFunc = FO_DELETE;
  428. file_op.pFrom = temp_path16.c_str();
  429. file_op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
  430. return (0 == SHFileOperation(&file_op));
  431. */
  432. } // namespace talk_base