file_util_unittest.cc 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "butil/build_config.h"
  5. #if defined(OS_WIN)
  6. #include <windows.h>
  7. #include <shellapi.h>
  8. #include <shlobj.h>
  9. #include <tchar.h>
  10. #include <winioctl.h>
  11. #endif
  12. #if defined(OS_POSIX)
  13. #include <errno.h>
  14. #include <fcntl.h>
  15. #include <unistd.h>
  16. #include <sys/types.h>
  17. #endif
  18. #include <algorithm>
  19. #include <fstream>
  20. #include <set>
  21. #include <vector>
  22. #include "butil/file_util.h"
  23. #include "butil/files/file_enumerator.h"
  24. #include "butil/files/file_path.h"
  25. #include "butil/files/scoped_file.h"
  26. #include "butil/files/scoped_temp_dir.h"
  27. #include "butil/strings/utf_string_conversions.h"
  28. #include "butil/threading/platform_thread.h"
  29. #include <gtest/gtest.h>
  30. #include <gtest/gtest.h>
  31. #if defined(OS_WIN)
  32. #include "butil/win/scoped_handle.h"
  33. #include "butil/win/windows_version.h"
  34. #endif
  35. #if defined(OS_ANDROID)
  36. #include "butil/android/content_uri_utils.h"
  37. #endif
  38. // This macro helps avoid wrapped lines in the test structs.
  39. #define FPL(x) FILE_PATH_LITERAL(x)
  40. namespace butil {
  41. namespace {
  42. // To test that file_util::Normalize FilePath() deals with NTFS reparse points
  43. // correctly, we need functions to create and delete reparse points.
  44. #if defined(OS_WIN)
  45. typedef struct _REPARSE_DATA_BUFFER {
  46. ULONG ReparseTag;
  47. USHORT ReparseDataLength;
  48. USHORT Reserved;
  49. union {
  50. struct {
  51. USHORT SubstituteNameOffset;
  52. USHORT SubstituteNameLength;
  53. USHORT PrintNameOffset;
  54. USHORT PrintNameLength;
  55. ULONG Flags;
  56. WCHAR PathBuffer[1];
  57. } SymbolicLinkReparseBuffer;
  58. struct {
  59. USHORT SubstituteNameOffset;
  60. USHORT SubstituteNameLength;
  61. USHORT PrintNameOffset;
  62. USHORT PrintNameLength;
  63. WCHAR PathBuffer[1];
  64. } MountPointReparseBuffer;
  65. struct {
  66. UCHAR DataBuffer[1];
  67. } GenericReparseBuffer;
  68. };
  69. } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
  70. // Sets a reparse point. |source| will now point to |target|. Returns true if
  71. // the call succeeds, false otherwise.
  72. bool SetReparsePoint(HANDLE source, const FilePath& target_path) {
  73. std::wstring kPathPrefix = L"\\??\\";
  74. std::wstring target_str;
  75. // The juction will not work if the target path does not start with \??\ .
  76. if (kPathPrefix != target_path.value().substr(0, kPathPrefix.size()))
  77. target_str += kPathPrefix;
  78. target_str += target_path.value();
  79. const wchar_t* target = target_str.c_str();
  80. USHORT size_target = static_cast<USHORT>(wcslen(target)) * sizeof(target[0]);
  81. char buffer[2000] = {0};
  82. DWORD returned;
  83. REPARSE_DATA_BUFFER* data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buffer);
  84. data->ReparseTag = 0xa0000003;
  85. memcpy(data->MountPointReparseBuffer.PathBuffer, target, size_target + 2);
  86. data->MountPointReparseBuffer.SubstituteNameLength = size_target;
  87. data->MountPointReparseBuffer.PrintNameOffset = size_target + 2;
  88. data->ReparseDataLength = size_target + 4 + 8;
  89. int data_size = data->ReparseDataLength + 8;
  90. if (!DeviceIoControl(source, FSCTL_SET_REPARSE_POINT, &buffer, data_size,
  91. NULL, 0, &returned, NULL)) {
  92. return false;
  93. }
  94. return true;
  95. }
  96. // Delete the reparse point referenced by |source|. Returns true if the call
  97. // succeeds, false otherwise.
  98. bool DeleteReparsePoint(HANDLE source) {
  99. DWORD returned;
  100. REPARSE_DATA_BUFFER data = {0};
  101. data.ReparseTag = 0xa0000003;
  102. if (!DeviceIoControl(source, FSCTL_DELETE_REPARSE_POINT, &data, 8, NULL, 0,
  103. &returned, NULL)) {
  104. return false;
  105. }
  106. return true;
  107. }
  108. // Manages a reparse point for a test.
  109. class ReparsePoint {
  110. public:
  111. // Creates a reparse point from |source| (an empty directory) to |target|.
  112. ReparsePoint(const FilePath& source, const FilePath& target) {
  113. dir_.Set(
  114. ::CreateFile(source.value().c_str(),
  115. FILE_ALL_ACCESS,
  116. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  117. NULL,
  118. OPEN_EXISTING,
  119. FILE_FLAG_BACKUP_SEMANTICS, // Needed to open a directory.
  120. NULL));
  121. created_ = dir_.IsValid() && SetReparsePoint(dir_, target);
  122. }
  123. ~ReparsePoint() {
  124. if (created_)
  125. DeleteReparsePoint(dir_);
  126. }
  127. bool IsValid() { return created_; }
  128. private:
  129. win::ScopedHandle dir_;
  130. bool created_;
  131. DISALLOW_COPY_AND_ASSIGN(ReparsePoint);
  132. };
  133. #endif
  134. #if defined(OS_POSIX)
  135. // Provide a simple way to change the permissions bits on |path| in tests.
  136. // ASSERT failures will return, but not stop the test. Caller should wrap
  137. // calls to this function in ASSERT_NO_FATAL_FAILURE().
  138. void ChangePosixFilePermissions(const FilePath& path,
  139. int mode_bits_to_set,
  140. int mode_bits_to_clear) {
  141. ASSERT_FALSE(mode_bits_to_set & mode_bits_to_clear)
  142. << "Can't set and clear the same bits.";
  143. int mode = 0;
  144. ASSERT_TRUE(GetPosixFilePermissions(path, &mode));
  145. mode |= mode_bits_to_set;
  146. mode &= ~mode_bits_to_clear;
  147. ASSERT_TRUE(SetPosixFilePermissions(path, mode));
  148. }
  149. #endif // defined(OS_POSIX)
  150. const wchar_t bogus_content[] = L"I'm cannon fodder.";
  151. const int FILES_AND_DIRECTORIES =
  152. FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
  153. // file_util winds up using autoreleased objects on the Mac, so this needs
  154. // to be a testing::Test
  155. class FileUtilTest : public testing::Test {
  156. protected:
  157. virtual void SetUp() OVERRIDE {
  158. #if defined(OS_POSIX)
  159. if (getuid() == 0) {
  160. is_root_ = true;
  161. ASSERT_EQ(0, setegid(65534));
  162. ASSERT_EQ(0, seteuid(65534));
  163. } else {
  164. is_root_ = false;
  165. }
  166. #endif
  167. testing::Test::SetUp();
  168. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  169. }
  170. #if defined(OS_POSIX)
  171. virtual void TearDown() OVERRIDE {
  172. if (is_root_) {
  173. ASSERT_EQ(0, seteuid(0));
  174. ASSERT_EQ(0, setegid(0));
  175. is_root_ = false;
  176. }
  177. testing::Test::TearDown();
  178. }
  179. #endif
  180. ScopedTempDir temp_dir_;
  181. #if defined(OS_POSIX)
  182. bool is_root_;
  183. #endif
  184. };
  185. // Collects all the results from the given file enumerator, and provides an
  186. // interface to query whether a given file is present.
  187. class FindResultCollector {
  188. public:
  189. explicit FindResultCollector(FileEnumerator& enumerator) {
  190. FilePath cur_file;
  191. while (!(cur_file = enumerator.Next()).value().empty()) {
  192. FilePath::StringType path = cur_file.value();
  193. // The file should not be returned twice.
  194. EXPECT_TRUE(files_.end() == files_.find(path))
  195. << "Same file returned twice";
  196. // Save for later.
  197. files_.insert(path);
  198. }
  199. }
  200. // Returns true if the enumerator found the file.
  201. bool HasFile(const FilePath& file) const {
  202. return files_.find(file.value()) != files_.end();
  203. }
  204. int size() {
  205. return static_cast<int>(files_.size());
  206. }
  207. private:
  208. std::set<FilePath::StringType> files_;
  209. };
  210. // Simple function to dump some text into a new file.
  211. void CreateTextFile(const FilePath& filename,
  212. const std::wstring& contents) {
  213. std::wofstream file;
  214. file.open(filename.value().c_str());
  215. ASSERT_TRUE(file.is_open());
  216. file << contents;
  217. file.close();
  218. }
  219. // Simple function to take out some text from a file.
  220. std::wstring ReadTextFile(const FilePath& filename) {
  221. wchar_t contents[64];
  222. std::wifstream file;
  223. file.open(filename.value().c_str());
  224. EXPECT_TRUE(file.is_open());
  225. file.getline(contents, arraysize(contents));
  226. file.close();
  227. return std::wstring(contents);
  228. }
  229. #if defined(OS_WIN)
  230. uint64_t FileTimeAsUint64(const FILETIME& ft) {
  231. ULARGE_INTEGER u;
  232. u.LowPart = ft.dwLowDateTime;
  233. u.HighPart = ft.dwHighDateTime;
  234. return u.QuadPart;
  235. }
  236. #endif
  237. TEST_F(FileUtilTest, FileAndDirectorySize) {
  238. // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
  239. // should return 53 bytes.
  240. FilePath file_01 = temp_dir_.path().Append(FPL("The file 01.txt"));
  241. CreateTextFile(file_01, L"12345678901234567890");
  242. int64_t size_f1 = 0;
  243. ASSERT_TRUE(GetFileSize(file_01, &size_f1));
  244. EXPECT_EQ(20ll, size_f1);
  245. FilePath subdir_path = temp_dir_.path().Append(FPL("Level2"));
  246. CreateDirectory(subdir_path);
  247. FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
  248. CreateTextFile(file_02, L"123456789012345678901234567890");
  249. int64_t size_f2 = 0;
  250. ASSERT_TRUE(GetFileSize(file_02, &size_f2));
  251. EXPECT_EQ(30ll, size_f2);
  252. FilePath subsubdir_path = subdir_path.Append(FPL("Level3"));
  253. CreateDirectory(subsubdir_path);
  254. FilePath file_03 = subsubdir_path.Append(FPL("The file 03.txt"));
  255. CreateTextFile(file_03, L"123");
  256. int64_t computed_size = ComputeDirectorySize(temp_dir_.path());
  257. EXPECT_EQ(size_f1 + size_f2 + 3, computed_size);
  258. }
  259. TEST_F(FileUtilTest, NormalizeFilePathBasic) {
  260. // Create a directory under the test dir. Because we create it,
  261. // we know it is not a link.
  262. FilePath file_a_path = temp_dir_.path().Append(FPL("file_a"));
  263. FilePath dir_path = temp_dir_.path().Append(FPL("dir"));
  264. FilePath file_b_path = dir_path.Append(FPL("file_b"));
  265. CreateDirectory(dir_path);
  266. FilePath normalized_file_a_path, normalized_file_b_path;
  267. ASSERT_FALSE(PathExists(file_a_path));
  268. ASSERT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
  269. << "NormalizeFilePath() should fail on nonexistent paths.";
  270. CreateTextFile(file_a_path, bogus_content);
  271. ASSERT_TRUE(PathExists(file_a_path));
  272. ASSERT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
  273. CreateTextFile(file_b_path, bogus_content);
  274. ASSERT_TRUE(PathExists(file_b_path));
  275. ASSERT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
  276. // Beacuse this test created |dir_path|, we know it is not a link
  277. // or junction. So, the real path of the directory holding file a
  278. // must be the parent of the path holding file b.
  279. ASSERT_TRUE(normalized_file_a_path.DirName()
  280. .IsParent(normalized_file_b_path.DirName()));
  281. }
  282. #if defined(OS_WIN)
  283. TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
  284. // Build the following directory structure:
  285. //
  286. // temp_dir
  287. // |-> base_a
  288. // | |-> sub_a
  289. // | |-> file.txt
  290. // | |-> long_name___... (Very long name.)
  291. // | |-> sub_long
  292. // | |-> deep.txt
  293. // |-> base_b
  294. // |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
  295. // |-> to_base_b (reparse point to temp_dir\base_b)
  296. // |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
  297. FilePath base_a = temp_dir_.path().Append(FPL("base_a"));
  298. ASSERT_TRUE(CreateDirectory(base_a));
  299. FilePath sub_a = base_a.Append(FPL("sub_a"));
  300. ASSERT_TRUE(CreateDirectory(sub_a));
  301. FilePath file_txt = sub_a.Append(FPL("file.txt"));
  302. CreateTextFile(file_txt, bogus_content);
  303. // Want a directory whose name is long enough to make the path to the file
  304. // inside just under MAX_PATH chars. This will be used to test that when
  305. // a junction expands to a path over MAX_PATH chars in length,
  306. // NormalizeFilePath() fails without crashing.
  307. FilePath sub_long_rel(FPL("sub_long"));
  308. FilePath deep_txt(FPL("deep.txt"));
  309. int target_length = MAX_PATH;
  310. target_length -= (sub_a.value().length() + 1); // +1 for the sepperator '\'.
  311. target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
  312. // Without making the path a bit shorter, CreateDirectory() fails.
  313. // the resulting path is still long enough to hit the failing case in
  314. // NormalizePath().
  315. const int kCreateDirLimit = 4;
  316. target_length -= kCreateDirLimit;
  317. FilePath::StringType long_name_str = FPL("long_name_");
  318. long_name_str.resize(target_length, '_');
  319. FilePath long_name = sub_a.Append(FilePath(long_name_str));
  320. FilePath deep_file = long_name.Append(sub_long_rel).Append(deep_txt);
  321. ASSERT_EQ(MAX_PATH - kCreateDirLimit, deep_file.value().length());
  322. FilePath sub_long = deep_file.DirName();
  323. ASSERT_TRUE(CreateDirectory(sub_long));
  324. CreateTextFile(deep_file, bogus_content);
  325. FilePath base_b = temp_dir_.path().Append(FPL("base_b"));
  326. ASSERT_TRUE(CreateDirectory(base_b));
  327. FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
  328. ASSERT_TRUE(CreateDirectory(to_sub_a));
  329. FilePath normalized_path;
  330. {
  331. ReparsePoint reparse_to_sub_a(to_sub_a, sub_a);
  332. ASSERT_TRUE(reparse_to_sub_a.IsValid());
  333. FilePath to_base_b = base_b.Append(FPL("to_base_b"));
  334. ASSERT_TRUE(CreateDirectory(to_base_b));
  335. ReparsePoint reparse_to_base_b(to_base_b, base_b);
  336. ASSERT_TRUE(reparse_to_base_b.IsValid());
  337. FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
  338. ASSERT_TRUE(CreateDirectory(to_sub_long));
  339. ReparsePoint reparse_to_sub_long(to_sub_long, sub_long);
  340. ASSERT_TRUE(reparse_to_sub_long.IsValid());
  341. // Normalize a junction free path: base_a\sub_a\file.txt .
  342. ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
  343. ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
  344. // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
  345. // the junction to_sub_a.
  346. ASSERT_TRUE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
  347. &normalized_path));
  348. ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
  349. // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
  350. // normalized to exclude junctions to_base_b and to_sub_a .
  351. ASSERT_TRUE(NormalizeFilePath(base_b.Append(FPL("to_base_b"))
  352. .Append(FPL("to_base_b"))
  353. .Append(FPL("to_sub_a"))
  354. .Append(FPL("file.txt")),
  355. &normalized_path));
  356. ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
  357. // A long enough path will cause NormalizeFilePath() to fail. Make a long
  358. // path using to_base_b many times, and check that paths long enough to fail
  359. // do not cause a crash.
  360. FilePath long_path = base_b;
  361. const int kLengthLimit = MAX_PATH + 200;
  362. while (long_path.value().length() <= kLengthLimit) {
  363. long_path = long_path.Append(FPL("to_base_b"));
  364. }
  365. long_path = long_path.Append(FPL("to_sub_a"))
  366. .Append(FPL("file.txt"));
  367. ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
  368. // Normalizing the junction to deep.txt should fail, because the expanded
  369. // path to deep.txt is longer than MAX_PATH.
  370. ASSERT_FALSE(NormalizeFilePath(to_sub_long.Append(deep_txt),
  371. &normalized_path));
  372. // Delete the reparse points, and see that NormalizeFilePath() fails
  373. // to traverse them.
  374. }
  375. ASSERT_FALSE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
  376. &normalized_path));
  377. }
  378. TEST_F(FileUtilTest, DevicePathToDriveLetter) {
  379. // Get a drive letter.
  380. std::wstring real_drive_letter = temp_dir_.path().value().substr(0, 2);
  381. if (!isalpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
  382. LOG(ERROR) << "Can't get a drive letter to test with.";
  383. return;
  384. }
  385. // Get the NT style path to that drive.
  386. wchar_t device_path[MAX_PATH] = {'\0'};
  387. ASSERT_TRUE(
  388. ::QueryDosDevice(real_drive_letter.c_str(), device_path, MAX_PATH));
  389. FilePath actual_device_path(device_path);
  390. FilePath win32_path;
  391. // Run DevicePathToDriveLetterPath() on the NT style path we got from
  392. // QueryDosDevice(). Expect the drive letter we started with.
  393. ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
  394. ASSERT_EQ(real_drive_letter, win32_path.value());
  395. // Add some directories to the path. Expect those extra path componenets
  396. // to be preserved.
  397. FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
  398. ASSERT_TRUE(DevicePathToDriveLetterPath(
  399. actual_device_path.Append(kRelativePath),
  400. &win32_path));
  401. EXPECT_EQ(FilePath(real_drive_letter + L"\\").Append(kRelativePath).value(),
  402. win32_path.value());
  403. // Deform the real path so that it is invalid by removing the last four
  404. // characters. The way windows names devices that are hard disks
  405. // (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
  406. // than three characters. The only way the truncated string could be a
  407. // real drive is if more than 10^3 disks are mounted:
  408. // \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
  409. // Check that DevicePathToDriveLetterPath fails.
  410. int path_length = actual_device_path.value().length();
  411. int new_length = path_length - 4;
  412. ASSERT_LT(0, new_length);
  413. FilePath prefix_of_real_device_path(
  414. actual_device_path.value().substr(0, new_length));
  415. ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path,
  416. &win32_path));
  417. ASSERT_FALSE(DevicePathToDriveLetterPath(
  418. prefix_of_real_device_path.Append(kRelativePath),
  419. &win32_path));
  420. // Deform the real path so that it is invalid by adding some characters. For
  421. // example, if C: maps to \Device\HardDiskVolume8, then we simulate a
  422. // request for the drive letter whose native path is
  423. // \Device\HardDiskVolume812345 . We assume such a device does not exist,
  424. // because drives are numbered in order and mounting 112345 hard disks will
  425. // never happen.
  426. const FilePath::StringType kExtraChars = FPL("12345");
  427. FilePath real_device_path_plus_numbers(
  428. actual_device_path.value() + kExtraChars);
  429. ASSERT_FALSE(DevicePathToDriveLetterPath(
  430. real_device_path_plus_numbers,
  431. &win32_path));
  432. ASSERT_FALSE(DevicePathToDriveLetterPath(
  433. real_device_path_plus_numbers.Append(kRelativePath),
  434. &win32_path));
  435. }
  436. TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
  437. // Test that CreateTemporaryFileInDir() creates a path and returns a long path
  438. // if it is available. This test requires that:
  439. // - the filesystem at |temp_dir_| supports long filenames.
  440. // - the account has FILE_LIST_DIRECTORY permission for all ancestor
  441. // directories of |temp_dir_|.
  442. const FilePath::CharType kLongDirName[] = FPL("A long path");
  443. const FilePath::CharType kTestSubDirName[] = FPL("test");
  444. FilePath long_test_dir = temp_dir_.path().Append(kLongDirName);
  445. ASSERT_TRUE(CreateDirectory(long_test_dir));
  446. // kLongDirName is not a 8.3 component. So GetShortName() should give us a
  447. // different short name.
  448. WCHAR path_buffer[MAX_PATH];
  449. DWORD path_buffer_length = GetShortPathName(long_test_dir.value().c_str(),
  450. path_buffer, MAX_PATH);
  451. ASSERT_LT(path_buffer_length, DWORD(MAX_PATH));
  452. ASSERT_NE(DWORD(0), path_buffer_length);
  453. FilePath short_test_dir(path_buffer);
  454. ASSERT_STRNE(kLongDirName, short_test_dir.BaseName().value().c_str());
  455. FilePath temp_file;
  456. ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
  457. EXPECT_STREQ(kLongDirName, temp_file.DirName().BaseName().value().c_str());
  458. EXPECT_TRUE(PathExists(temp_file));
  459. // Create a subdirectory of |long_test_dir| and make |long_test_dir|
  460. // unreadable. We should still be able to create a temp file in the
  461. // subdirectory, but we won't be able to determine the long path for it. This
  462. // mimics the environment that some users run where their user profiles reside
  463. // in a location where the don't have full access to the higher level
  464. // directories. (Note that this assumption is true for NTFS, but not for some
  465. // network file systems. E.g. AFS).
  466. FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
  467. ASSERT_TRUE(CreateDirectory(access_test_dir));
  468. file_util::PermissionRestorer long_test_dir_restorer(long_test_dir);
  469. ASSERT_TRUE(file_util::MakeFileUnreadable(long_test_dir));
  470. // Use the short form of the directory to create a temporary filename.
  471. ASSERT_TRUE(CreateTemporaryFileInDir(
  472. short_test_dir.Append(kTestSubDirName), &temp_file));
  473. EXPECT_TRUE(PathExists(temp_file));
  474. EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
  475. // Check that the long path can't be determined for |temp_file|.
  476. path_buffer_length = GetLongPathName(temp_file.value().c_str(),
  477. path_buffer, MAX_PATH);
  478. EXPECT_EQ(DWORD(0), path_buffer_length);
  479. }
  480. #endif // defined(OS_WIN)
  481. #if defined(OS_POSIX)
  482. TEST_F(FileUtilTest, CreateAndReadSymlinks) {
  483. FilePath link_from = temp_dir_.path().Append(FPL("from_file"));
  484. FilePath link_to = temp_dir_.path().Append(FPL("to_file"));
  485. CreateTextFile(link_to, bogus_content);
  486. ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
  487. << "Failed to create file symlink.";
  488. // If we created the link properly, we should be able to read the contents
  489. // through it.
  490. std::wstring contents = ReadTextFile(link_from);
  491. EXPECT_EQ(bogus_content, contents);
  492. FilePath result;
  493. ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
  494. EXPECT_EQ(link_to.value(), result.value());
  495. // Link to a directory.
  496. link_from = temp_dir_.path().Append(FPL("from_dir"));
  497. link_to = temp_dir_.path().Append(FPL("to_dir"));
  498. ASSERT_TRUE(CreateDirectory(link_to));
  499. ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
  500. << "Failed to create directory symlink.";
  501. // Test failures.
  502. EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
  503. EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
  504. FilePath missing = temp_dir_.path().Append(FPL("missing"));
  505. EXPECT_FALSE(ReadSymbolicLink(missing, &result));
  506. }
  507. // The following test of NormalizeFilePath() require that we create a symlink.
  508. // This can not be done on Windows before Vista. On Vista, creating a symlink
  509. // requires privilege "SeCreateSymbolicLinkPrivilege".
  510. // TODO(skerner): Investigate the possibility of giving base_unittests the
  511. // privileges required to create a symlink.
  512. TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
  513. // Link one file to another.
  514. FilePath link_from = temp_dir_.path().Append(FPL("from_file"));
  515. FilePath link_to = temp_dir_.path().Append(FPL("to_file"));
  516. CreateTextFile(link_to, bogus_content);
  517. ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
  518. << "Failed to create file symlink.";
  519. // Check that NormalizeFilePath sees the link.
  520. FilePath normalized_path;
  521. ASSERT_TRUE(NormalizeFilePath(link_from, &normalized_path));
  522. EXPECT_NE(link_from, link_to);
  523. EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
  524. EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
  525. // Link to a directory.
  526. link_from = temp_dir_.path().Append(FPL("from_dir"));
  527. link_to = temp_dir_.path().Append(FPL("to_dir"));
  528. ASSERT_TRUE(CreateDirectory(link_to));
  529. ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
  530. << "Failed to create directory symlink.";
  531. EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path))
  532. << "Links to directories should return false.";
  533. // Test that a loop in the links causes NormalizeFilePath() to return false.
  534. link_from = temp_dir_.path().Append(FPL("link_a"));
  535. link_to = temp_dir_.path().Append(FPL("link_b"));
  536. ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
  537. << "Failed to create loop symlink a.";
  538. ASSERT_TRUE(CreateSymbolicLink(link_from, link_to))
  539. << "Failed to create loop symlink b.";
  540. // Infinite loop!
  541. EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
  542. }
  543. #endif // defined(OS_POSIX)
  544. TEST_F(FileUtilTest, DeleteNonExistent) {
  545. FilePath non_existent = temp_dir_.path().AppendASCII("bogus_file_dne.foobar");
  546. ASSERT_FALSE(PathExists(non_existent));
  547. EXPECT_TRUE(DeleteFile(non_existent, false));
  548. ASSERT_FALSE(PathExists(non_existent));
  549. EXPECT_TRUE(DeleteFile(non_existent, true));
  550. ASSERT_FALSE(PathExists(non_existent));
  551. }
  552. TEST_F(FileUtilTest, DeleteNonExistentWithNonExistentParent) {
  553. FilePath non_existent = temp_dir_.path().AppendASCII("bogus_topdir");
  554. non_existent = non_existent.AppendASCII("bogus_subdir");
  555. ASSERT_FALSE(PathExists(non_existent));
  556. EXPECT_TRUE(DeleteFile(non_existent, false));
  557. ASSERT_FALSE(PathExists(non_existent));
  558. EXPECT_TRUE(DeleteFile(non_existent, true));
  559. ASSERT_FALSE(PathExists(non_existent));
  560. }
  561. TEST_F(FileUtilTest, DeleteFile) {
  562. // Create a file
  563. FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteFile 1.txt"));
  564. CreateTextFile(file_name, bogus_content);
  565. ASSERT_TRUE(PathExists(file_name));
  566. // Make sure it's deleted
  567. EXPECT_TRUE(DeleteFile(file_name, false));
  568. EXPECT_FALSE(PathExists(file_name));
  569. // Test recursive case, create a new file
  570. file_name = temp_dir_.path().Append(FPL("Test DeleteFile 2.txt"));
  571. CreateTextFile(file_name, bogus_content);
  572. ASSERT_TRUE(PathExists(file_name));
  573. // Make sure it's deleted
  574. EXPECT_TRUE(DeleteFile(file_name, true));
  575. EXPECT_FALSE(PathExists(file_name));
  576. }
  577. #if defined(OS_POSIX)
  578. TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
  579. // Create a file.
  580. FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteFile 2.txt"));
  581. CreateTextFile(file_name, bogus_content);
  582. ASSERT_TRUE(PathExists(file_name));
  583. // Create a symlink to the file.
  584. FilePath file_link = temp_dir_.path().Append("file_link_2");
  585. ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
  586. << "Failed to create symlink.";
  587. // Delete the symbolic link.
  588. EXPECT_TRUE(DeleteFile(file_link, false));
  589. // Make sure original file is not deleted.
  590. EXPECT_FALSE(PathExists(file_link));
  591. EXPECT_TRUE(PathExists(file_name));
  592. }
  593. TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
  594. // Create a non-existent file path.
  595. FilePath non_existent = temp_dir_.path().Append(FPL("Test DeleteFile 3.txt"));
  596. EXPECT_FALSE(PathExists(non_existent));
  597. // Create a symlink to the non-existent file.
  598. FilePath file_link = temp_dir_.path().Append("file_link_3");
  599. ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
  600. << "Failed to create symlink.";
  601. // Make sure the symbolic link is exist.
  602. EXPECT_TRUE(IsLink(file_link));
  603. EXPECT_FALSE(PathExists(file_link));
  604. // Delete the symbolic link.
  605. EXPECT_TRUE(DeleteFile(file_link, false));
  606. // Make sure the symbolic link is deleted.
  607. EXPECT_FALSE(IsLink(file_link));
  608. }
  609. TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
  610. // Create a file path.
  611. FilePath file_name = temp_dir_.path().Append(FPL("Test Readable File.txt"));
  612. EXPECT_FALSE(PathExists(file_name));
  613. const std::string kData("hello");
  614. int buffer_size = kData.length();
  615. char* buffer = new char[buffer_size];
  616. // Write file.
  617. EXPECT_EQ(static_cast<int>(kData.length()),
  618. WriteFile(file_name, kData.data(), kData.length()));
  619. EXPECT_TRUE(PathExists(file_name));
  620. // Make sure the file is readable.
  621. int32_t mode = 0;
  622. EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
  623. EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
  624. // Get rid of the read permission.
  625. EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
  626. EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
  627. EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
  628. // Make sure the file can't be read.
  629. EXPECT_EQ(-1, ReadFile(file_name, buffer, buffer_size));
  630. // Give the read permission.
  631. EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
  632. EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
  633. EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
  634. // Make sure the file can be read.
  635. EXPECT_EQ(static_cast<int>(kData.length()),
  636. ReadFile(file_name, buffer, buffer_size));
  637. // Delete the file.
  638. EXPECT_TRUE(DeleteFile(file_name, false));
  639. EXPECT_FALSE(PathExists(file_name));
  640. delete[] buffer;
  641. }
  642. TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
  643. // Create a file path.
  644. FilePath file_name = temp_dir_.path().Append(FPL("Test Readable File.txt"));
  645. EXPECT_FALSE(PathExists(file_name));
  646. const std::string kData("hello");
  647. // Write file.
  648. EXPECT_EQ(static_cast<int>(kData.length()),
  649. WriteFile(file_name, kData.data(), kData.length()));
  650. EXPECT_TRUE(PathExists(file_name));
  651. // Make sure the file is writable.
  652. int mode = 0;
  653. EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
  654. EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
  655. EXPECT_TRUE(PathIsWritable(file_name));
  656. // Get rid of the write permission.
  657. EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
  658. EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
  659. EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
  660. // Make sure the file can't be write.
  661. EXPECT_EQ(-1, WriteFile(file_name, kData.data(), kData.length()));
  662. if (!is_root_) {
  663. EXPECT_FALSE(PathIsWritable(file_name));
  664. }
  665. // Give read permission.
  666. EXPECT_TRUE(SetPosixFilePermissions(file_name,
  667. FILE_PERMISSION_WRITE_BY_USER));
  668. EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
  669. EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
  670. // Make sure the file can be write.
  671. EXPECT_EQ(static_cast<int>(kData.length()),
  672. WriteFile(file_name, kData.data(), kData.length()));
  673. EXPECT_TRUE(PathIsWritable(file_name));
  674. // Delete the file.
  675. EXPECT_TRUE(DeleteFile(file_name, false));
  676. EXPECT_FALSE(PathExists(file_name));
  677. }
  678. TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
  679. // Create a directory path.
  680. FilePath subdir_path =
  681. temp_dir_.path().Append(FPL("PermissionTest1"));
  682. CreateDirectory(subdir_path);
  683. ASSERT_TRUE(PathExists(subdir_path));
  684. // Create a dummy file to enumerate.
  685. FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
  686. EXPECT_FALSE(PathExists(file_name));
  687. const std::string kData("hello");
  688. EXPECT_EQ(static_cast<int>(kData.length()),
  689. WriteFile(file_name, kData.data(), kData.length()));
  690. EXPECT_TRUE(PathExists(file_name));
  691. // Make sure the directory has the all permissions.
  692. int mode = 0;
  693. EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
  694. EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
  695. // Get rid of the permissions from the directory.
  696. EXPECT_TRUE(SetPosixFilePermissions(subdir_path, 0u));
  697. EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
  698. EXPECT_FALSE(mode & FILE_PERMISSION_USER_MASK);
  699. // Make sure the file in the directory can't be enumerated.
  700. FileEnumerator f1(subdir_path, true, FileEnumerator::FILES);
  701. EXPECT_TRUE(PathExists(subdir_path));
  702. FindResultCollector c1(f1);
  703. EXPECT_EQ(0, c1.size());
  704. EXPECT_FALSE(GetPosixFilePermissions(file_name, &mode));
  705. // Give the permissions to the directory.
  706. EXPECT_TRUE(SetPosixFilePermissions(subdir_path, FILE_PERMISSION_USER_MASK));
  707. EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
  708. EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
  709. // Make sure the file in the directory can be enumerated.
  710. FileEnumerator f2(subdir_path, true, FileEnumerator::FILES);
  711. FindResultCollector c2(f2);
  712. EXPECT_TRUE(c2.HasFile(file_name));
  713. EXPECT_EQ(1, c2.size());
  714. // Delete the file.
  715. EXPECT_TRUE(DeleteFile(subdir_path, true));
  716. EXPECT_FALSE(PathExists(subdir_path));
  717. }
  718. #endif // defined(OS_POSIX)
  719. #if defined(OS_WIN)
  720. // Tests that the Delete function works for wild cards, especially
  721. // with the recursion flag. Also coincidentally tests PathExists.
  722. // TODO(erikkay): see if anyone's actually using this feature of the API
  723. TEST_F(FileUtilTest, DeleteWildCard) {
  724. // Create a file and a directory
  725. FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteWildCard.txt"));
  726. CreateTextFile(file_name, bogus_content);
  727. ASSERT_TRUE(PathExists(file_name));
  728. FilePath subdir_path = temp_dir_.path().Append(FPL("DeleteWildCardDir"));
  729. CreateDirectory(subdir_path);
  730. ASSERT_TRUE(PathExists(subdir_path));
  731. // Create the wildcard path
  732. FilePath directory_contents = temp_dir_.path();
  733. directory_contents = directory_contents.Append(FPL("*"));
  734. // Delete non-recursively and check that only the file is deleted
  735. EXPECT_TRUE(DeleteFile(directory_contents, false));
  736. EXPECT_FALSE(PathExists(file_name));
  737. EXPECT_TRUE(PathExists(subdir_path));
  738. // Delete recursively and make sure all contents are deleted
  739. EXPECT_TRUE(DeleteFile(directory_contents, true));
  740. EXPECT_FALSE(PathExists(file_name));
  741. EXPECT_FALSE(PathExists(subdir_path));
  742. }
  743. // TODO(erikkay): see if anyone's actually using this feature of the API
  744. TEST_F(FileUtilTest, DeleteNonExistantWildCard) {
  745. // Create a file and a directory
  746. FilePath subdir_path =
  747. temp_dir_.path().Append(FPL("DeleteNonExistantWildCard"));
  748. CreateDirectory(subdir_path);
  749. ASSERT_TRUE(PathExists(subdir_path));
  750. // Create the wildcard path
  751. FilePath directory_contents = subdir_path;
  752. directory_contents = directory_contents.Append(FPL("*"));
  753. // Delete non-recursively and check nothing got deleted
  754. EXPECT_TRUE(DeleteFile(directory_contents, false));
  755. EXPECT_TRUE(PathExists(subdir_path));
  756. // Delete recursively and check nothing got deleted
  757. EXPECT_TRUE(DeleteFile(directory_contents, true));
  758. EXPECT_TRUE(PathExists(subdir_path));
  759. }
  760. #endif
  761. // Tests non-recursive Delete() for a directory.
  762. TEST_F(FileUtilTest, DeleteDirNonRecursive) {
  763. // Create a subdirectory and put a file and two directories inside.
  764. FilePath test_subdir = temp_dir_.path().Append(FPL("DeleteDirNonRecursive"));
  765. CreateDirectory(test_subdir);
  766. ASSERT_TRUE(PathExists(test_subdir));
  767. FilePath file_name = test_subdir.Append(FPL("Test DeleteDir.txt"));
  768. CreateTextFile(file_name, bogus_content);
  769. ASSERT_TRUE(PathExists(file_name));
  770. FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
  771. CreateDirectory(subdir_path1);
  772. ASSERT_TRUE(PathExists(subdir_path1));
  773. FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
  774. CreateDirectory(subdir_path2);
  775. ASSERT_TRUE(PathExists(subdir_path2));
  776. // Delete non-recursively and check that the empty dir got deleted
  777. EXPECT_TRUE(DeleteFile(subdir_path2, false));
  778. EXPECT_FALSE(PathExists(subdir_path2));
  779. // Delete non-recursively and check that nothing got deleted
  780. EXPECT_FALSE(DeleteFile(test_subdir, false));
  781. EXPECT_TRUE(PathExists(test_subdir));
  782. EXPECT_TRUE(PathExists(file_name));
  783. EXPECT_TRUE(PathExists(subdir_path1));
  784. }
  785. // Tests recursive Delete() for a directory.
  786. TEST_F(FileUtilTest, DeleteDirRecursive) {
  787. // Create a subdirectory and put a file and two directories inside.
  788. FilePath test_subdir = temp_dir_.path().Append(FPL("DeleteDirRecursive"));
  789. CreateDirectory(test_subdir);
  790. ASSERT_TRUE(PathExists(test_subdir));
  791. FilePath file_name = test_subdir.Append(FPL("Test DeleteDirRecursive.txt"));
  792. CreateTextFile(file_name, bogus_content);
  793. ASSERT_TRUE(PathExists(file_name));
  794. FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
  795. CreateDirectory(subdir_path1);
  796. ASSERT_TRUE(PathExists(subdir_path1));
  797. FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
  798. CreateDirectory(subdir_path2);
  799. ASSERT_TRUE(PathExists(subdir_path2));
  800. // Delete recursively and check that the empty dir got deleted
  801. EXPECT_TRUE(DeleteFile(subdir_path2, true));
  802. EXPECT_FALSE(PathExists(subdir_path2));
  803. // Delete recursively and check that everything got deleted
  804. EXPECT_TRUE(DeleteFile(test_subdir, true));
  805. EXPECT_FALSE(PathExists(file_name));
  806. EXPECT_FALSE(PathExists(subdir_path1));
  807. EXPECT_FALSE(PathExists(test_subdir));
  808. }
  809. TEST_F(FileUtilTest, MoveFileNew) {
  810. // Create a file
  811. FilePath file_name_from =
  812. temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
  813. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  814. ASSERT_TRUE(PathExists(file_name_from));
  815. // The destination.
  816. FilePath file_name_to = temp_dir_.path().Append(
  817. FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
  818. ASSERT_FALSE(PathExists(file_name_to));
  819. EXPECT_TRUE(Move(file_name_from, file_name_to));
  820. // Check everything has been moved.
  821. EXPECT_FALSE(PathExists(file_name_from));
  822. EXPECT_TRUE(PathExists(file_name_to));
  823. }
  824. TEST_F(FileUtilTest, MoveFileExists) {
  825. // Create a file
  826. FilePath file_name_from =
  827. temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
  828. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  829. ASSERT_TRUE(PathExists(file_name_from));
  830. // The destination name.
  831. FilePath file_name_to = temp_dir_.path().Append(
  832. FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
  833. CreateTextFile(file_name_to, L"Old file content");
  834. ASSERT_TRUE(PathExists(file_name_to));
  835. EXPECT_TRUE(Move(file_name_from, file_name_to));
  836. // Check everything has been moved.
  837. EXPECT_FALSE(PathExists(file_name_from));
  838. EXPECT_TRUE(PathExists(file_name_to));
  839. EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
  840. }
  841. TEST_F(FileUtilTest, MoveFileDirExists) {
  842. // Create a file
  843. FilePath file_name_from =
  844. temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
  845. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  846. ASSERT_TRUE(PathExists(file_name_from));
  847. // The destination directory
  848. FilePath dir_name_to =
  849. temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
  850. CreateDirectory(dir_name_to);
  851. ASSERT_TRUE(PathExists(dir_name_to));
  852. EXPECT_FALSE(Move(file_name_from, dir_name_to));
  853. }
  854. TEST_F(FileUtilTest, MoveNew) {
  855. // Create a directory
  856. FilePath dir_name_from =
  857. temp_dir_.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
  858. CreateDirectory(dir_name_from);
  859. ASSERT_TRUE(PathExists(dir_name_from));
  860. // Create a file under the directory
  861. FilePath txt_file_name(FILE_PATH_LITERAL("Move_Test_File.txt"));
  862. FilePath file_name_from = dir_name_from.Append(txt_file_name);
  863. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  864. ASSERT_TRUE(PathExists(file_name_from));
  865. // Move the directory.
  866. FilePath dir_name_to =
  867. temp_dir_.path().Append(FILE_PATH_LITERAL("Move_To_Subdir"));
  868. FilePath file_name_to =
  869. dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
  870. ASSERT_FALSE(PathExists(dir_name_to));
  871. EXPECT_TRUE(Move(dir_name_from, dir_name_to));
  872. // Check everything has been moved.
  873. EXPECT_FALSE(PathExists(dir_name_from));
  874. EXPECT_FALSE(PathExists(file_name_from));
  875. EXPECT_TRUE(PathExists(dir_name_to));
  876. EXPECT_TRUE(PathExists(file_name_to));
  877. // Test path traversal.
  878. file_name_from = dir_name_to.Append(txt_file_name);
  879. file_name_to = dir_name_to.Append(FILE_PATH_LITERAL(".."));
  880. file_name_to = file_name_to.Append(txt_file_name);
  881. EXPECT_FALSE(Move(file_name_from, file_name_to));
  882. EXPECT_TRUE(PathExists(file_name_from));
  883. EXPECT_FALSE(PathExists(file_name_to));
  884. EXPECT_TRUE(internal::MoveUnsafe(file_name_from, file_name_to));
  885. EXPECT_FALSE(PathExists(file_name_from));
  886. EXPECT_TRUE(PathExists(file_name_to));
  887. }
  888. TEST_F(FileUtilTest, MoveExist) {
  889. // Create a directory
  890. FilePath dir_name_from =
  891. temp_dir_.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
  892. CreateDirectory(dir_name_from);
  893. ASSERT_TRUE(PathExists(dir_name_from));
  894. // Create a file under the directory
  895. FilePath file_name_from =
  896. dir_name_from.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
  897. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  898. ASSERT_TRUE(PathExists(file_name_from));
  899. // Move the directory
  900. FilePath dir_name_exists =
  901. temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
  902. FilePath dir_name_to =
  903. dir_name_exists.Append(FILE_PATH_LITERAL("Move_To_Subdir"));
  904. FilePath file_name_to =
  905. dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
  906. // Create the destination directory.
  907. CreateDirectory(dir_name_exists);
  908. ASSERT_TRUE(PathExists(dir_name_exists));
  909. EXPECT_TRUE(Move(dir_name_from, dir_name_to));
  910. // Check everything has been moved.
  911. EXPECT_FALSE(PathExists(dir_name_from));
  912. EXPECT_FALSE(PathExists(file_name_from));
  913. EXPECT_TRUE(PathExists(dir_name_to));
  914. EXPECT_TRUE(PathExists(file_name_to));
  915. }
  916. TEST_F(FileUtilTest, CopyDirectoryRecursivelyNew) {
  917. // Create a directory.
  918. FilePath dir_name_from =
  919. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  920. CreateDirectory(dir_name_from);
  921. ASSERT_TRUE(PathExists(dir_name_from));
  922. // Create a file under the directory.
  923. FilePath file_name_from =
  924. dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  925. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  926. ASSERT_TRUE(PathExists(file_name_from));
  927. // Create a subdirectory.
  928. FilePath subdir_name_from =
  929. dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
  930. CreateDirectory(subdir_name_from);
  931. ASSERT_TRUE(PathExists(subdir_name_from));
  932. // Create a file under the subdirectory.
  933. FilePath file_name2_from =
  934. subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  935. CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
  936. ASSERT_TRUE(PathExists(file_name2_from));
  937. // Copy the directory recursively.
  938. FilePath dir_name_to =
  939. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
  940. FilePath file_name_to =
  941. dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  942. FilePath subdir_name_to =
  943. dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
  944. FilePath file_name2_to =
  945. subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  946. ASSERT_FALSE(PathExists(dir_name_to));
  947. EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
  948. // Check everything has been copied.
  949. EXPECT_TRUE(PathExists(dir_name_from));
  950. EXPECT_TRUE(PathExists(file_name_from));
  951. EXPECT_TRUE(PathExists(subdir_name_from));
  952. EXPECT_TRUE(PathExists(file_name2_from));
  953. EXPECT_TRUE(PathExists(dir_name_to));
  954. EXPECT_TRUE(PathExists(file_name_to));
  955. EXPECT_TRUE(PathExists(subdir_name_to));
  956. EXPECT_TRUE(PathExists(file_name2_to));
  957. }
  958. TEST_F(FileUtilTest, CopyDirectoryRecursivelyExists) {
  959. // Create a directory.
  960. FilePath dir_name_from =
  961. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  962. CreateDirectory(dir_name_from);
  963. ASSERT_TRUE(PathExists(dir_name_from));
  964. // Create a file under the directory.
  965. FilePath file_name_from =
  966. dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  967. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  968. ASSERT_TRUE(PathExists(file_name_from));
  969. // Create a subdirectory.
  970. FilePath subdir_name_from =
  971. dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
  972. CreateDirectory(subdir_name_from);
  973. ASSERT_TRUE(PathExists(subdir_name_from));
  974. // Create a file under the subdirectory.
  975. FilePath file_name2_from =
  976. subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  977. CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
  978. ASSERT_TRUE(PathExists(file_name2_from));
  979. // Copy the directory recursively.
  980. FilePath dir_name_exists =
  981. temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
  982. FilePath dir_name_to =
  983. dir_name_exists.Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  984. FilePath file_name_to =
  985. dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  986. FilePath subdir_name_to =
  987. dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
  988. FilePath file_name2_to =
  989. subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  990. // Create the destination directory.
  991. CreateDirectory(dir_name_exists);
  992. ASSERT_TRUE(PathExists(dir_name_exists));
  993. EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_exists, true));
  994. // Check everything has been copied.
  995. EXPECT_TRUE(PathExists(dir_name_from));
  996. EXPECT_TRUE(PathExists(file_name_from));
  997. EXPECT_TRUE(PathExists(subdir_name_from));
  998. EXPECT_TRUE(PathExists(file_name2_from));
  999. EXPECT_TRUE(PathExists(dir_name_to));
  1000. EXPECT_TRUE(PathExists(file_name_to));
  1001. EXPECT_TRUE(PathExists(subdir_name_to));
  1002. EXPECT_TRUE(PathExists(file_name2_to));
  1003. }
  1004. TEST_F(FileUtilTest, CopyDirectoryNew) {
  1005. // Create a directory.
  1006. FilePath dir_name_from =
  1007. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  1008. CreateDirectory(dir_name_from);
  1009. ASSERT_TRUE(PathExists(dir_name_from));
  1010. // Create a file under the directory.
  1011. FilePath file_name_from =
  1012. dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1013. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1014. ASSERT_TRUE(PathExists(file_name_from));
  1015. // Create a subdirectory.
  1016. FilePath subdir_name_from =
  1017. dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
  1018. CreateDirectory(subdir_name_from);
  1019. ASSERT_TRUE(PathExists(subdir_name_from));
  1020. // Create a file under the subdirectory.
  1021. FilePath file_name2_from =
  1022. subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1023. CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
  1024. ASSERT_TRUE(PathExists(file_name2_from));
  1025. // Copy the directory not recursively.
  1026. FilePath dir_name_to =
  1027. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
  1028. FilePath file_name_to =
  1029. dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1030. FilePath subdir_name_to =
  1031. dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
  1032. ASSERT_FALSE(PathExists(dir_name_to));
  1033. EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
  1034. // Check everything has been copied.
  1035. EXPECT_TRUE(PathExists(dir_name_from));
  1036. EXPECT_TRUE(PathExists(file_name_from));
  1037. EXPECT_TRUE(PathExists(subdir_name_from));
  1038. EXPECT_TRUE(PathExists(file_name2_from));
  1039. EXPECT_TRUE(PathExists(dir_name_to));
  1040. EXPECT_TRUE(PathExists(file_name_to));
  1041. EXPECT_FALSE(PathExists(subdir_name_to));
  1042. }
  1043. TEST_F(FileUtilTest, CopyDirectoryExists) {
  1044. // Create a directory.
  1045. FilePath dir_name_from =
  1046. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  1047. CreateDirectory(dir_name_from);
  1048. ASSERT_TRUE(PathExists(dir_name_from));
  1049. // Create a file under the directory.
  1050. FilePath file_name_from =
  1051. dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1052. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1053. ASSERT_TRUE(PathExists(file_name_from));
  1054. // Create a subdirectory.
  1055. FilePath subdir_name_from =
  1056. dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
  1057. CreateDirectory(subdir_name_from);
  1058. ASSERT_TRUE(PathExists(subdir_name_from));
  1059. // Create a file under the subdirectory.
  1060. FilePath file_name2_from =
  1061. subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1062. CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
  1063. ASSERT_TRUE(PathExists(file_name2_from));
  1064. // Copy the directory not recursively.
  1065. FilePath dir_name_to =
  1066. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
  1067. FilePath file_name_to =
  1068. dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1069. FilePath subdir_name_to =
  1070. dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
  1071. // Create the destination directory.
  1072. CreateDirectory(dir_name_to);
  1073. ASSERT_TRUE(PathExists(dir_name_to));
  1074. EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
  1075. // Check everything has been copied.
  1076. EXPECT_TRUE(PathExists(dir_name_from));
  1077. EXPECT_TRUE(PathExists(file_name_from));
  1078. EXPECT_TRUE(PathExists(subdir_name_from));
  1079. EXPECT_TRUE(PathExists(file_name2_from));
  1080. EXPECT_TRUE(PathExists(dir_name_to));
  1081. EXPECT_TRUE(PathExists(file_name_to));
  1082. EXPECT_FALSE(PathExists(subdir_name_to));
  1083. }
  1084. TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToNew) {
  1085. // Create a file
  1086. FilePath file_name_from =
  1087. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1088. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1089. ASSERT_TRUE(PathExists(file_name_from));
  1090. // The destination name
  1091. FilePath file_name_to = temp_dir_.path().Append(
  1092. FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
  1093. ASSERT_FALSE(PathExists(file_name_to));
  1094. EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
  1095. // Check the has been copied
  1096. EXPECT_TRUE(PathExists(file_name_to));
  1097. }
  1098. TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExisting) {
  1099. // Create a file
  1100. FilePath file_name_from =
  1101. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1102. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1103. ASSERT_TRUE(PathExists(file_name_from));
  1104. // The destination name
  1105. FilePath file_name_to = temp_dir_.path().Append(
  1106. FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
  1107. CreateTextFile(file_name_to, L"Old file content");
  1108. ASSERT_TRUE(PathExists(file_name_to));
  1109. EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
  1110. // Check the has been copied
  1111. EXPECT_TRUE(PathExists(file_name_to));
  1112. EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
  1113. }
  1114. TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExistingDirectory) {
  1115. // Create a file
  1116. FilePath file_name_from =
  1117. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1118. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1119. ASSERT_TRUE(PathExists(file_name_from));
  1120. // The destination
  1121. FilePath dir_name_to =
  1122. temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
  1123. CreateDirectory(dir_name_to);
  1124. ASSERT_TRUE(PathExists(dir_name_to));
  1125. FilePath file_name_to =
  1126. dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1127. EXPECT_TRUE(CopyDirectory(file_name_from, dir_name_to, true));
  1128. // Check the has been copied
  1129. EXPECT_TRUE(PathExists(file_name_to));
  1130. }
  1131. TEST_F(FileUtilTest, CopyDirectoryWithTrailingSeparators) {
  1132. // Create a directory.
  1133. FilePath dir_name_from =
  1134. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  1135. CreateDirectory(dir_name_from);
  1136. ASSERT_TRUE(PathExists(dir_name_from));
  1137. // Create a file under the directory.
  1138. FilePath file_name_from =
  1139. dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1140. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1141. ASSERT_TRUE(PathExists(file_name_from));
  1142. // Copy the directory recursively.
  1143. FilePath dir_name_to =
  1144. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
  1145. FilePath file_name_to =
  1146. dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1147. // Create from path with trailing separators.
  1148. #if defined(OS_WIN)
  1149. FilePath from_path =
  1150. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
  1151. #elif defined (OS_POSIX)
  1152. FilePath from_path =
  1153. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
  1154. #endif
  1155. EXPECT_TRUE(CopyDirectory(from_path, dir_name_to, true));
  1156. // Check everything has been copied.
  1157. EXPECT_TRUE(PathExists(dir_name_from));
  1158. EXPECT_TRUE(PathExists(file_name_from));
  1159. EXPECT_TRUE(PathExists(dir_name_to));
  1160. EXPECT_TRUE(PathExists(file_name_to));
  1161. }
  1162. // Sets the source file to read-only.
  1163. void SetReadOnly(const FilePath& path) {
  1164. #if defined(OS_WIN)
  1165. // On Windows, it involves setting a bit.
  1166. DWORD attrs = GetFileAttributes(path.value().c_str());
  1167. ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
  1168. ASSERT_TRUE(SetFileAttributes(
  1169. path.value().c_str(), attrs | FILE_ATTRIBUTE_READONLY));
  1170. attrs = GetFileAttributes(path.value().c_str());
  1171. // Files in the temporary directory should not be indexed ever. If this
  1172. // assumption change, fix this unit test accordingly.
  1173. // FILE_ATTRIBUTE_NOT_CONTENT_INDEXED doesn't exist on XP.
  1174. DWORD expected = FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_READONLY;
  1175. if (win::GetVersion() >= win::VERSION_VISTA)
  1176. expected |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
  1177. ASSERT_EQ(expected, attrs);
  1178. #else
  1179. // On all other platforms, it involves removing the write bit.
  1180. EXPECT_TRUE(SetPosixFilePermissions(path, S_IRUSR));
  1181. #endif
  1182. }
  1183. bool IsReadOnly(const FilePath& path) {
  1184. #if defined(OS_WIN)
  1185. DWORD attrs = GetFileAttributes(path.value().c_str());
  1186. EXPECT_NE(INVALID_FILE_ATTRIBUTES, attrs);
  1187. return attrs & FILE_ATTRIBUTE_READONLY;
  1188. #else
  1189. int mode = 0;
  1190. EXPECT_TRUE(GetPosixFilePermissions(path, &mode));
  1191. return !(mode & S_IWUSR);
  1192. #endif
  1193. }
  1194. TEST_F(FileUtilTest, CopyDirectoryACL) {
  1195. // Create a directory.
  1196. FilePath src = temp_dir_.path().Append(FILE_PATH_LITERAL("src"));
  1197. CreateDirectory(src);
  1198. ASSERT_TRUE(PathExists(src));
  1199. // Create a file under the directory.
  1200. FilePath src_file = src.Append(FILE_PATH_LITERAL("src.txt"));
  1201. CreateTextFile(src_file, L"Gooooooooooooooooooooogle");
  1202. SetReadOnly(src_file);
  1203. ASSERT_TRUE(IsReadOnly(src_file));
  1204. // Copy the directory recursively.
  1205. FilePath dst = temp_dir_.path().Append(FILE_PATH_LITERAL("dst"));
  1206. FilePath dst_file = dst.Append(FILE_PATH_LITERAL("src.txt"));
  1207. EXPECT_TRUE(CopyDirectory(src, dst, true));
  1208. ASSERT_FALSE(IsReadOnly(dst_file));
  1209. }
  1210. TEST_F(FileUtilTest, CopyFile) {
  1211. // Create a directory
  1212. FilePath dir_name_from =
  1213. temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
  1214. CreateDirectory(dir_name_from);
  1215. ASSERT_TRUE(PathExists(dir_name_from));
  1216. // Create a file under the directory
  1217. FilePath file_name_from =
  1218. dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
  1219. const std::wstring file_contents(L"Gooooooooooooooooooooogle");
  1220. CreateTextFile(file_name_from, file_contents);
  1221. ASSERT_TRUE(PathExists(file_name_from));
  1222. // Copy the file.
  1223. FilePath dest_file = dir_name_from.Append(FILE_PATH_LITERAL("DestFile.txt"));
  1224. ASSERT_TRUE(CopyFile(file_name_from, dest_file));
  1225. // Copy the file to another location using '..' in the path.
  1226. FilePath dest_file2(dir_name_from);
  1227. dest_file2 = dest_file2.AppendASCII("..");
  1228. dest_file2 = dest_file2.AppendASCII("DestFile.txt");
  1229. ASSERT_FALSE(CopyFile(file_name_from, dest_file2));
  1230. ASSERT_TRUE(internal::CopyFileUnsafe(file_name_from, dest_file2));
  1231. FilePath dest_file2_test(dir_name_from);
  1232. dest_file2_test = dest_file2_test.DirName();
  1233. dest_file2_test = dest_file2_test.AppendASCII("DestFile.txt");
  1234. // Check everything has been copied.
  1235. EXPECT_TRUE(PathExists(file_name_from));
  1236. EXPECT_TRUE(PathExists(dest_file));
  1237. const std::wstring read_contents = ReadTextFile(dest_file);
  1238. EXPECT_EQ(file_contents, read_contents);
  1239. EXPECT_TRUE(PathExists(dest_file2_test));
  1240. EXPECT_TRUE(PathExists(dest_file2));
  1241. }
  1242. TEST_F(FileUtilTest, CopyFileACL) {
  1243. // While FileUtilTest.CopyFile asserts the content is correctly copied over,
  1244. // this test case asserts the access control bits are meeting expectations in
  1245. // CopyFileUnsafe().
  1246. FilePath src = temp_dir_.path().Append(FILE_PATH_LITERAL("src.txt"));
  1247. const std::wstring file_contents(L"Gooooooooooooooooooooogle");
  1248. CreateTextFile(src, file_contents);
  1249. // Set the source file to read-only.
  1250. ASSERT_FALSE(IsReadOnly(src));
  1251. SetReadOnly(src);
  1252. ASSERT_TRUE(IsReadOnly(src));
  1253. // Copy the file.
  1254. FilePath dst = temp_dir_.path().Append(FILE_PATH_LITERAL("dst.txt"));
  1255. ASSERT_TRUE(CopyFile(src, dst));
  1256. EXPECT_EQ(file_contents, ReadTextFile(dst));
  1257. ASSERT_FALSE(IsReadOnly(dst));
  1258. }
  1259. // file_util winds up using autoreleased objects on the Mac, so this needs
  1260. // to be a testing::Test.
  1261. typedef testing::Test ReadOnlyFileUtilTest;
  1262. #if defined(FixedContentsEqual)
  1263. TEST_F(ReadOnlyFileUtilTest, ContentsEqual) {
  1264. FilePath data_dir;
  1265. ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
  1266. data_dir = data_dir.AppendASCII("file_util");
  1267. ASSERT_TRUE(PathExists(data_dir));
  1268. FilePath original_file =
  1269. data_dir.Append(FILE_PATH_LITERAL("original.txt"));
  1270. FilePath same_file =
  1271. data_dir.Append(FILE_PATH_LITERAL("same.txt"));
  1272. FilePath same_length_file =
  1273. data_dir.Append(FILE_PATH_LITERAL("same_length.txt"));
  1274. FilePath different_file =
  1275. data_dir.Append(FILE_PATH_LITERAL("different.txt"));
  1276. FilePath different_first_file =
  1277. data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
  1278. FilePath different_last_file =
  1279. data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
  1280. FilePath empty1_file =
  1281. data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
  1282. FilePath empty2_file =
  1283. data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
  1284. FilePath shortened_file =
  1285. data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
  1286. FilePath binary_file =
  1287. data_dir.Append(FILE_PATH_LITERAL("binary_file.bin"));
  1288. FilePath binary_file_same =
  1289. data_dir.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
  1290. FilePath binary_file_diff =
  1291. data_dir.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
  1292. EXPECT_TRUE(ContentsEqual(original_file, original_file));
  1293. EXPECT_TRUE(ContentsEqual(original_file, same_file));
  1294. EXPECT_FALSE(ContentsEqual(original_file, same_length_file));
  1295. EXPECT_FALSE(ContentsEqual(original_file, different_file));
  1296. EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
  1297. FilePath(FILE_PATH_LITERAL("bogusname"))));
  1298. EXPECT_FALSE(ContentsEqual(original_file, different_first_file));
  1299. EXPECT_FALSE(ContentsEqual(original_file, different_last_file));
  1300. EXPECT_TRUE(ContentsEqual(empty1_file, empty2_file));
  1301. EXPECT_FALSE(ContentsEqual(original_file, shortened_file));
  1302. EXPECT_FALSE(ContentsEqual(shortened_file, original_file));
  1303. EXPECT_TRUE(ContentsEqual(binary_file, binary_file_same));
  1304. EXPECT_FALSE(ContentsEqual(binary_file, binary_file_diff));
  1305. }
  1306. #endif
  1307. #if defined(FixedTextContentsEqual)
  1308. TEST_F(ReadOnlyFileUtilTest, TextContentsEqual) {
  1309. FilePath data_dir;
  1310. ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
  1311. data_dir = data_dir.AppendASCII("file_util");
  1312. ASSERT_TRUE(PathExists(data_dir));
  1313. FilePath original_file =
  1314. data_dir.Append(FILE_PATH_LITERAL("original.txt"));
  1315. FilePath same_file =
  1316. data_dir.Append(FILE_PATH_LITERAL("same.txt"));
  1317. FilePath crlf_file =
  1318. data_dir.Append(FILE_PATH_LITERAL("crlf.txt"));
  1319. FilePath shortened_file =
  1320. data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
  1321. FilePath different_file =
  1322. data_dir.Append(FILE_PATH_LITERAL("different.txt"));
  1323. FilePath different_first_file =
  1324. data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
  1325. FilePath different_last_file =
  1326. data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
  1327. FilePath first1_file =
  1328. data_dir.Append(FILE_PATH_LITERAL("first1.txt"));
  1329. FilePath first2_file =
  1330. data_dir.Append(FILE_PATH_LITERAL("first2.txt"));
  1331. FilePath empty1_file =
  1332. data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
  1333. FilePath empty2_file =
  1334. data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
  1335. FilePath blank_line_file =
  1336. data_dir.Append(FILE_PATH_LITERAL("blank_line.txt"));
  1337. FilePath blank_line_crlf_file =
  1338. data_dir.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
  1339. EXPECT_TRUE(TextContentsEqual(original_file, same_file));
  1340. EXPECT_TRUE(TextContentsEqual(original_file, crlf_file));
  1341. EXPECT_FALSE(TextContentsEqual(original_file, shortened_file));
  1342. EXPECT_FALSE(TextContentsEqual(original_file, different_file));
  1343. EXPECT_FALSE(TextContentsEqual(original_file, different_first_file));
  1344. EXPECT_FALSE(TextContentsEqual(original_file, different_last_file));
  1345. EXPECT_FALSE(TextContentsEqual(first1_file, first2_file));
  1346. EXPECT_TRUE(TextContentsEqual(empty1_file, empty2_file));
  1347. EXPECT_FALSE(TextContentsEqual(original_file, empty1_file));
  1348. EXPECT_TRUE(TextContentsEqual(blank_line_file, blank_line_crlf_file));
  1349. }
  1350. #endif
  1351. // We don't need equivalent functionality outside of Windows.
  1352. #if defined(OS_WIN)
  1353. TEST_F(FileUtilTest, CopyAndDeleteDirectoryTest) {
  1354. // Create a directory
  1355. FilePath dir_name_from =
  1356. temp_dir_.path().Append(FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
  1357. CreateDirectory(dir_name_from);
  1358. ASSERT_TRUE(PathExists(dir_name_from));
  1359. // Create a file under the directory
  1360. FilePath file_name_from =
  1361. dir_name_from.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
  1362. CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
  1363. ASSERT_TRUE(PathExists(file_name_from));
  1364. // Move the directory by using CopyAndDeleteDirectory
  1365. FilePath dir_name_to = temp_dir_.path().Append(
  1366. FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
  1367. FilePath file_name_to =
  1368. dir_name_to.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
  1369. ASSERT_FALSE(PathExists(dir_name_to));
  1370. EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from,
  1371. dir_name_to));
  1372. // Check everything has been moved.
  1373. EXPECT_FALSE(PathExists(dir_name_from));
  1374. EXPECT_FALSE(PathExists(file_name_from));
  1375. EXPECT_TRUE(PathExists(dir_name_to));
  1376. EXPECT_TRUE(PathExists(file_name_to));
  1377. }
  1378. TEST_F(FileUtilTest, GetTempDirTest) {
  1379. static const TCHAR* kTmpKey = _T("TMP");
  1380. static const TCHAR* kTmpValues[] = {
  1381. _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
  1382. };
  1383. // Save the original $TMP.
  1384. size_t original_tmp_size;
  1385. TCHAR* original_tmp;
  1386. ASSERT_EQ(0, ::_tdupenv_s(&original_tmp, &original_tmp_size, kTmpKey));
  1387. // original_tmp may be NULL.
  1388. for (unsigned int i = 0; i < arraysize(kTmpValues); ++i) {
  1389. FilePath path;
  1390. ::_tputenv_s(kTmpKey, kTmpValues[i]);
  1391. GetTempDir(&path);
  1392. EXPECT_TRUE(path.IsAbsolute()) << "$TMP=" << kTmpValues[i] <<
  1393. " result=" << path.value();
  1394. }
  1395. // Restore the original $TMP.
  1396. if (original_tmp) {
  1397. ::_tputenv_s(kTmpKey, original_tmp);
  1398. free(original_tmp);
  1399. } else {
  1400. ::_tputenv_s(kTmpKey, _T(""));
  1401. }
  1402. }
  1403. #endif // OS_WIN
  1404. TEST_F(FileUtilTest, CreateTemporaryFileTest) {
  1405. FilePath temp_files[3];
  1406. for (int i = 0; i < 3; i++) {
  1407. ASSERT_TRUE(CreateTemporaryFile(&(temp_files[i])));
  1408. EXPECT_TRUE(PathExists(temp_files[i]));
  1409. EXPECT_FALSE(DirectoryExists(temp_files[i]));
  1410. }
  1411. for (int i = 0; i < 3; i++)
  1412. EXPECT_FALSE(temp_files[i] == temp_files[(i+1)%3]);
  1413. for (int i = 0; i < 3; i++)
  1414. EXPECT_TRUE(DeleteFile(temp_files[i], false));
  1415. }
  1416. TEST_F(FileUtilTest, CreateAndOpenTemporaryFileTest) {
  1417. FilePath names[3];
  1418. FILE* fps[3];
  1419. int i;
  1420. // Create; make sure they are open and exist.
  1421. for (i = 0; i < 3; ++i) {
  1422. fps[i] = CreateAndOpenTemporaryFile(&(names[i]));
  1423. ASSERT_TRUE(fps[i]);
  1424. EXPECT_TRUE(PathExists(names[i]));
  1425. }
  1426. // Make sure all names are unique.
  1427. for (i = 0; i < 3; ++i) {
  1428. EXPECT_FALSE(names[i] == names[(i+1)%3]);
  1429. }
  1430. // Close and delete.
  1431. for (i = 0; i < 3; ++i) {
  1432. EXPECT_TRUE(CloseFile(fps[i]));
  1433. EXPECT_TRUE(DeleteFile(names[i], false));
  1434. }
  1435. }
  1436. TEST_F(FileUtilTest, FileToFILE) {
  1437. File file;
  1438. FILE* stream = FileToFILE(file.Pass(), "w");
  1439. EXPECT_FALSE(stream);
  1440. FilePath file_name = temp_dir_.path().Append(FPL("The file.txt"));
  1441. file = File(file_name, File::FLAG_CREATE | File::FLAG_WRITE);
  1442. EXPECT_TRUE(file.IsValid());
  1443. stream = FileToFILE(file.Pass(), "w");
  1444. EXPECT_TRUE(stream);
  1445. EXPECT_FALSE(file.IsValid());
  1446. EXPECT_TRUE(CloseFile(stream));
  1447. }
  1448. TEST_F(FileUtilTest, CreateNewTempDirectoryTest) {
  1449. FilePath temp_dir;
  1450. ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir));
  1451. EXPECT_TRUE(PathExists(temp_dir));
  1452. EXPECT_TRUE(DeleteFile(temp_dir, false));
  1453. }
  1454. TEST_F(FileUtilTest, CreateNewTemporaryDirInDirTest) {
  1455. FilePath new_dir;
  1456. ASSERT_TRUE(CreateTemporaryDirInDir(
  1457. temp_dir_.path(),
  1458. FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
  1459. &new_dir));
  1460. EXPECT_TRUE(PathExists(new_dir));
  1461. EXPECT_TRUE(temp_dir_.path().IsParent(new_dir));
  1462. EXPECT_TRUE(DeleteFile(new_dir, false));
  1463. }
  1464. #if defined(OS_POSIX)
  1465. TEST_F(FileUtilTest, GetShmemTempDirTest) {
  1466. FilePath dir;
  1467. EXPECT_TRUE(GetShmemTempDir(false, &dir));
  1468. EXPECT_TRUE(DirectoryExists(dir));
  1469. }
  1470. #endif
  1471. TEST_F(FileUtilTest, GetHomeDirTest) {
  1472. #if !defined(OS_ANDROID) // Not implemented on Android.
  1473. // We don't actually know what the home directory is supposed to be without
  1474. // calling some OS functions which would just duplicate the implementation.
  1475. // So here we just test that it returns something "reasonable".
  1476. FilePath home = GetHomeDir();
  1477. ASSERT_FALSE(home.empty());
  1478. ASSERT_TRUE(home.IsAbsolute());
  1479. #endif
  1480. }
  1481. TEST_F(FileUtilTest, CreateDirectoryTest) {
  1482. FilePath test_root =
  1483. temp_dir_.path().Append(FILE_PATH_LITERAL("create_directory_test"));
  1484. #if defined(OS_WIN)
  1485. FilePath test_path =
  1486. test_root.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
  1487. #elif defined(OS_POSIX)
  1488. FilePath test_path =
  1489. test_root.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
  1490. #endif
  1491. EXPECT_FALSE(PathExists(test_path));
  1492. EXPECT_TRUE(CreateDirectory(test_path));
  1493. EXPECT_TRUE(PathExists(test_path));
  1494. // CreateDirectory returns true if the DirectoryExists returns true.
  1495. EXPECT_TRUE(CreateDirectory(test_path));
  1496. // Doesn't work to create it on top of a non-dir
  1497. test_path = test_path.Append(FILE_PATH_LITERAL("foobar.txt"));
  1498. EXPECT_FALSE(PathExists(test_path));
  1499. CreateTextFile(test_path, L"test file");
  1500. EXPECT_TRUE(PathExists(test_path));
  1501. EXPECT_FALSE(CreateDirectory(test_path));
  1502. EXPECT_TRUE(DeleteFile(test_root, true));
  1503. EXPECT_FALSE(PathExists(test_root));
  1504. EXPECT_FALSE(PathExists(test_path));
  1505. // Verify assumptions made by the Windows implementation:
  1506. // 1. The current directory always exists.
  1507. // 2. The root directory always exists.
  1508. ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory)));
  1509. FilePath top_level = test_root;
  1510. while (top_level != top_level.DirName()) {
  1511. top_level = top_level.DirName();
  1512. }
  1513. ASSERT_TRUE(DirectoryExists(top_level));
  1514. // Given these assumptions hold, it should be safe to
  1515. // test that "creating" these directories succeeds.
  1516. EXPECT_TRUE(CreateDirectory(
  1517. FilePath(FilePath::kCurrentDirectory)));
  1518. EXPECT_TRUE(CreateDirectory(top_level));
  1519. #if defined(OS_WIN)
  1520. FilePath invalid_drive(FILE_PATH_LITERAL("o:\\"));
  1521. FilePath invalid_path =
  1522. invalid_drive.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
  1523. if (!PathExists(invalid_drive)) {
  1524. EXPECT_FALSE(CreateDirectory(invalid_path));
  1525. }
  1526. #endif
  1527. }
  1528. TEST_F(FileUtilTest, DetectDirectoryTest) {
  1529. // Check a directory
  1530. FilePath test_root =
  1531. temp_dir_.path().Append(FILE_PATH_LITERAL("detect_directory_test"));
  1532. EXPECT_FALSE(PathExists(test_root));
  1533. EXPECT_TRUE(CreateDirectory(test_root));
  1534. EXPECT_TRUE(PathExists(test_root));
  1535. EXPECT_TRUE(DirectoryExists(test_root));
  1536. // Check a file
  1537. FilePath test_path =
  1538. test_root.Append(FILE_PATH_LITERAL("foobar.txt"));
  1539. EXPECT_FALSE(PathExists(test_path));
  1540. CreateTextFile(test_path, L"test file");
  1541. EXPECT_TRUE(PathExists(test_path));
  1542. EXPECT_FALSE(DirectoryExists(test_path));
  1543. EXPECT_TRUE(DeleteFile(test_path, false));
  1544. EXPECT_TRUE(DeleteFile(test_root, true));
  1545. }
  1546. TEST_F(FileUtilTest, FileEnumeratorTest) {
  1547. // Test an empty directory.
  1548. FileEnumerator f0(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
  1549. EXPECT_EQ(FPL(""), f0.Next().value());
  1550. EXPECT_EQ(FPL(""), f0.Next().value());
  1551. // Test an empty directory, non-recursively, including "..".
  1552. FileEnumerator f0_dotdot(temp_dir_.path(), false,
  1553. FILES_AND_DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
  1554. EXPECT_EQ(temp_dir_.path().Append(FPL("..")).value(),
  1555. f0_dotdot.Next().value());
  1556. EXPECT_EQ(FPL(""), f0_dotdot.Next().value());
  1557. // create the directories
  1558. FilePath dir1 = temp_dir_.path().Append(FPL("dir1"));
  1559. EXPECT_TRUE(CreateDirectory(dir1));
  1560. FilePath dir2 = temp_dir_.path().Append(FPL("dir2"));
  1561. EXPECT_TRUE(CreateDirectory(dir2));
  1562. FilePath dir2inner = dir2.Append(FPL("inner"));
  1563. EXPECT_TRUE(CreateDirectory(dir2inner));
  1564. // create the files
  1565. FilePath dir2file = dir2.Append(FPL("dir2file.txt"));
  1566. CreateTextFile(dir2file, std::wstring());
  1567. FilePath dir2innerfile = dir2inner.Append(FPL("innerfile.txt"));
  1568. CreateTextFile(dir2innerfile, std::wstring());
  1569. FilePath file1 = temp_dir_.path().Append(FPL("file1.txt"));
  1570. CreateTextFile(file1, std::wstring());
  1571. FilePath file2_rel = dir2.Append(FilePath::kParentDirectory)
  1572. .Append(FPL("file2.txt"));
  1573. CreateTextFile(file2_rel, std::wstring());
  1574. FilePath file2_abs = temp_dir_.path().Append(FPL("file2.txt"));
  1575. // Only enumerate files.
  1576. FileEnumerator f1(temp_dir_.path(), true, FileEnumerator::FILES);
  1577. FindResultCollector c1(f1);
  1578. EXPECT_TRUE(c1.HasFile(file1));
  1579. EXPECT_TRUE(c1.HasFile(file2_abs));
  1580. EXPECT_TRUE(c1.HasFile(dir2file));
  1581. EXPECT_TRUE(c1.HasFile(dir2innerfile));
  1582. EXPECT_EQ(4, c1.size());
  1583. // Only enumerate directories.
  1584. FileEnumerator f2(temp_dir_.path(), true, FileEnumerator::DIRECTORIES);
  1585. FindResultCollector c2(f2);
  1586. EXPECT_TRUE(c2.HasFile(dir1));
  1587. EXPECT_TRUE(c2.HasFile(dir2));
  1588. EXPECT_TRUE(c2.HasFile(dir2inner));
  1589. EXPECT_EQ(3, c2.size());
  1590. // Only enumerate directories non-recursively.
  1591. FileEnumerator f2_non_recursive(
  1592. temp_dir_.path(), false, FileEnumerator::DIRECTORIES);
  1593. FindResultCollector c2_non_recursive(f2_non_recursive);
  1594. EXPECT_TRUE(c2_non_recursive.HasFile(dir1));
  1595. EXPECT_TRUE(c2_non_recursive.HasFile(dir2));
  1596. EXPECT_EQ(2, c2_non_recursive.size());
  1597. // Only enumerate directories, non-recursively, including "..".
  1598. FileEnumerator f2_dotdot(temp_dir_.path(), false,
  1599. FileEnumerator::DIRECTORIES |
  1600. FileEnumerator::INCLUDE_DOT_DOT);
  1601. FindResultCollector c2_dotdot(f2_dotdot);
  1602. EXPECT_TRUE(c2_dotdot.HasFile(dir1));
  1603. EXPECT_TRUE(c2_dotdot.HasFile(dir2));
  1604. EXPECT_TRUE(c2_dotdot.HasFile(temp_dir_.path().Append(FPL(".."))));
  1605. EXPECT_EQ(3, c2_dotdot.size());
  1606. // Enumerate files and directories.
  1607. FileEnumerator f3(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
  1608. FindResultCollector c3(f3);
  1609. EXPECT_TRUE(c3.HasFile(dir1));
  1610. EXPECT_TRUE(c3.HasFile(dir2));
  1611. EXPECT_TRUE(c3.HasFile(file1));
  1612. EXPECT_TRUE(c3.HasFile(file2_abs));
  1613. EXPECT_TRUE(c3.HasFile(dir2file));
  1614. EXPECT_TRUE(c3.HasFile(dir2inner));
  1615. EXPECT_TRUE(c3.HasFile(dir2innerfile));
  1616. EXPECT_EQ(7, c3.size());
  1617. // Non-recursive operation.
  1618. FileEnumerator f4(temp_dir_.path(), false, FILES_AND_DIRECTORIES);
  1619. FindResultCollector c4(f4);
  1620. EXPECT_TRUE(c4.HasFile(dir2));
  1621. EXPECT_TRUE(c4.HasFile(dir2));
  1622. EXPECT_TRUE(c4.HasFile(file1));
  1623. EXPECT_TRUE(c4.HasFile(file2_abs));
  1624. EXPECT_EQ(4, c4.size());
  1625. // Enumerate with a pattern.
  1626. FileEnumerator f5(temp_dir_.path(), true, FILES_AND_DIRECTORIES, FPL("dir*"));
  1627. FindResultCollector c5(f5);
  1628. EXPECT_TRUE(c5.HasFile(dir1));
  1629. EXPECT_TRUE(c5.HasFile(dir2));
  1630. EXPECT_TRUE(c5.HasFile(dir2file));
  1631. EXPECT_TRUE(c5.HasFile(dir2inner));
  1632. EXPECT_TRUE(c5.HasFile(dir2innerfile));
  1633. EXPECT_EQ(5, c5.size());
  1634. #if defined(OS_WIN)
  1635. {
  1636. // Make dir1 point to dir2.
  1637. ReparsePoint reparse_point(dir1, dir2);
  1638. EXPECT_TRUE(reparse_point.IsValid());
  1639. if ((win::GetVersion() >= win::VERSION_VISTA)) {
  1640. // There can be a delay for the enumeration code to see the change on
  1641. // the file system so skip this test for XP.
  1642. // Enumerate the reparse point.
  1643. FileEnumerator f6(dir1, true, FILES_AND_DIRECTORIES);
  1644. FindResultCollector c6(f6);
  1645. FilePath inner2 = dir1.Append(FPL("inner"));
  1646. EXPECT_TRUE(c6.HasFile(inner2));
  1647. EXPECT_TRUE(c6.HasFile(inner2.Append(FPL("innerfile.txt"))));
  1648. EXPECT_TRUE(c6.HasFile(dir1.Append(FPL("dir2file.txt"))));
  1649. EXPECT_EQ(3, c6.size());
  1650. }
  1651. // No changes for non recursive operation.
  1652. FileEnumerator f7(temp_dir_.path(), false, FILES_AND_DIRECTORIES);
  1653. FindResultCollector c7(f7);
  1654. EXPECT_TRUE(c7.HasFile(dir2));
  1655. EXPECT_TRUE(c7.HasFile(dir2));
  1656. EXPECT_TRUE(c7.HasFile(file1));
  1657. EXPECT_TRUE(c7.HasFile(file2_abs));
  1658. EXPECT_EQ(4, c7.size());
  1659. // Should not enumerate inside dir1 when using recursion.
  1660. FileEnumerator f8(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
  1661. FindResultCollector c8(f8);
  1662. EXPECT_TRUE(c8.HasFile(dir1));
  1663. EXPECT_TRUE(c8.HasFile(dir2));
  1664. EXPECT_TRUE(c8.HasFile(file1));
  1665. EXPECT_TRUE(c8.HasFile(file2_abs));
  1666. EXPECT_TRUE(c8.HasFile(dir2file));
  1667. EXPECT_TRUE(c8.HasFile(dir2inner));
  1668. EXPECT_TRUE(c8.HasFile(dir2innerfile));
  1669. EXPECT_EQ(7, c8.size());
  1670. }
  1671. #endif
  1672. // Make sure the destructor closes the find handle while in the middle of a
  1673. // query to allow TearDown to delete the directory.
  1674. FileEnumerator f9(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
  1675. EXPECT_FALSE(f9.Next().value().empty()); // Should have found something
  1676. // (we don't care what).
  1677. }
  1678. TEST_F(FileUtilTest, AppendToFile) {
  1679. FilePath data_dir =
  1680. temp_dir_.path().Append(FILE_PATH_LITERAL("FilePathTest"));
  1681. // Create a fresh, empty copy of this directory.
  1682. if (PathExists(data_dir)) {
  1683. ASSERT_TRUE(DeleteFile(data_dir, true));
  1684. }
  1685. ASSERT_TRUE(CreateDirectory(data_dir));
  1686. // Create a fresh, empty copy of this directory.
  1687. if (PathExists(data_dir)) {
  1688. ASSERT_TRUE(DeleteFile(data_dir, true));
  1689. }
  1690. ASSERT_TRUE(CreateDirectory(data_dir));
  1691. FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
  1692. std::string data("hello");
  1693. EXPECT_EQ(-1, AppendToFile(foobar, data.c_str(), data.length()));
  1694. EXPECT_EQ(static_cast<int>(data.length()),
  1695. WriteFile(foobar, data.c_str(), data.length()));
  1696. EXPECT_EQ(static_cast<int>(data.length()),
  1697. AppendToFile(foobar, data.c_str(), data.length()));
  1698. const std::wstring read_content = ReadTextFile(foobar);
  1699. EXPECT_EQ(L"hellohello", read_content);
  1700. }
  1701. TEST_F(FileUtilTest, ReadFile) {
  1702. // Create a test file to be read.
  1703. const std::string kTestData("The quick brown fox jumps over the lazy dog.");
  1704. FilePath file_path =
  1705. temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileTest"));
  1706. ASSERT_EQ(static_cast<int>(kTestData.size()),
  1707. WriteFile(file_path, kTestData.data(), kTestData.size()));
  1708. // Make buffers with various size.
  1709. std::vector<char> small_buffer(kTestData.size() / 2);
  1710. std::vector<char> exact_buffer(kTestData.size());
  1711. std::vector<char> large_buffer(kTestData.size() * 2);
  1712. // Read the file with smaller buffer.
  1713. int bytes_read_small = ReadFile(
  1714. file_path, &small_buffer[0], static_cast<int>(small_buffer.size()));
  1715. EXPECT_EQ(static_cast<int>(small_buffer.size()), bytes_read_small);
  1716. EXPECT_EQ(
  1717. std::string(kTestData.begin(), kTestData.begin() + small_buffer.size()),
  1718. std::string(small_buffer.begin(), small_buffer.end()));
  1719. // Read the file with buffer which have exactly same size.
  1720. int bytes_read_exact = ReadFile(
  1721. file_path, &exact_buffer[0], static_cast<int>(exact_buffer.size()));
  1722. EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_exact);
  1723. EXPECT_EQ(kTestData, std::string(exact_buffer.begin(), exact_buffer.end()));
  1724. // Read the file with larger buffer.
  1725. int bytes_read_large = ReadFile(
  1726. file_path, &large_buffer[0], static_cast<int>(large_buffer.size()));
  1727. EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_large);
  1728. EXPECT_EQ(kTestData, std::string(large_buffer.begin(),
  1729. large_buffer.begin() + kTestData.size()));
  1730. // Make sure the return value is -1 if the file doesn't exist.
  1731. FilePath file_path_not_exist =
  1732. temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
  1733. EXPECT_EQ(-1,
  1734. ReadFile(file_path_not_exist,
  1735. &exact_buffer[0],
  1736. static_cast<int>(exact_buffer.size())));
  1737. }
  1738. TEST_F(FileUtilTest, ReadFileToString) {
  1739. const char kTestData[] = "0123";
  1740. std::string data;
  1741. FilePath file_path =
  1742. temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
  1743. FilePath file_path_dangerous =
  1744. temp_dir_.path().Append(FILE_PATH_LITERAL("..")).
  1745. Append(temp_dir_.path().BaseName()).
  1746. Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
  1747. // Create test file.
  1748. ASSERT_EQ(4, WriteFile(file_path, kTestData, 4));
  1749. EXPECT_TRUE(ReadFileToString(file_path, &data));
  1750. EXPECT_EQ(kTestData, data);
  1751. data = "temp";
  1752. EXPECT_FALSE(ReadFileToString(file_path, &data, 0));
  1753. EXPECT_EQ(0u, data.length());
  1754. data = "temp";
  1755. EXPECT_FALSE(ReadFileToString(file_path, &data, 2));
  1756. EXPECT_EQ("01", data);
  1757. data.clear();
  1758. EXPECT_FALSE(ReadFileToString(file_path, &data, 3));
  1759. EXPECT_EQ("012", data);
  1760. data.clear();
  1761. EXPECT_TRUE(ReadFileToString(file_path, &data, 4));
  1762. EXPECT_EQ("0123", data);
  1763. data.clear();
  1764. EXPECT_TRUE(ReadFileToString(file_path, &data, 6));
  1765. EXPECT_EQ("0123", data);
  1766. EXPECT_TRUE(ReadFileToString(file_path, NULL, 6));
  1767. EXPECT_TRUE(ReadFileToString(file_path, NULL));
  1768. data = "temp";
  1769. EXPECT_FALSE(ReadFileToString(file_path_dangerous, &data));
  1770. EXPECT_EQ(0u, data.length());
  1771. // Delete test file.
  1772. EXPECT_TRUE(butil::DeleteFile(file_path, false));
  1773. data = "temp";
  1774. EXPECT_FALSE(ReadFileToString(file_path, &data));
  1775. EXPECT_EQ(0u, data.length());
  1776. data = "temp";
  1777. EXPECT_FALSE(ReadFileToString(file_path, &data, 6));
  1778. EXPECT_EQ(0u, data.length());
  1779. }
  1780. TEST_F(FileUtilTest, TouchFile) {
  1781. FilePath data_dir =
  1782. temp_dir_.path().Append(FILE_PATH_LITERAL("FilePathTest"));
  1783. // Create a fresh, empty copy of this directory.
  1784. if (PathExists(data_dir)) {
  1785. ASSERT_TRUE(DeleteFile(data_dir, true));
  1786. }
  1787. ASSERT_TRUE(CreateDirectory(data_dir));
  1788. FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
  1789. std::string data("hello");
  1790. ASSERT_TRUE(WriteFile(foobar, data.c_str(), data.length()));
  1791. // 784915200000000 represents the timestamp of "Wed, 16 Nov 1994, 00:00:00".
  1792. // This timestamp is divisible by one day (in local timezone), to make it work
  1793. // on FAT too.
  1794. auto access_time = Time::FromUTCExploded({1994, 11, 4, 16, 0, 0, 0, 0});
  1795. // 784903526000000 represents the timestamp of "Tue, 15 Nov 1994, 12:45:26 GMT".
  1796. // Note that this timestamp is divisible by two (seconds) - FAT stores
  1797. // modification times with 2s resolution.
  1798. auto modification_time = Time::FromUTCExploded({1994, 11, 3, 15, 12, 45, 26, 0});
  1799. ASSERT_TRUE(TouchFile(foobar, access_time, modification_time));
  1800. File::Info file_info;
  1801. ASSERT_TRUE(GetFileInfo(foobar, &file_info));
  1802. EXPECT_EQ(access_time.ToInternalValue(),
  1803. file_info.last_accessed.ToInternalValue());
  1804. EXPECT_EQ(modification_time.ToInternalValue(),
  1805. file_info.last_modified.ToInternalValue());
  1806. }
  1807. TEST_F(FileUtilTest, IsDirectoryEmpty) {
  1808. FilePath empty_dir = temp_dir_.path().Append(FILE_PATH_LITERAL("EmptyDir"));
  1809. ASSERT_FALSE(PathExists(empty_dir));
  1810. ASSERT_TRUE(CreateDirectory(empty_dir));
  1811. EXPECT_TRUE(IsDirectoryEmpty(empty_dir));
  1812. FilePath foo(empty_dir.Append(FILE_PATH_LITERAL("foo.txt")));
  1813. std::string bar("baz");
  1814. ASSERT_TRUE(WriteFile(foo, bar.c_str(), bar.length()));
  1815. EXPECT_FALSE(IsDirectoryEmpty(empty_dir));
  1816. }
  1817. #if defined(OS_POSIX)
  1818. // Testing VerifyPathControlledByAdmin() is hard, because there is no
  1819. // way a test can make a file owned by root, or change file paths
  1820. // at the root of the file system. VerifyPathControlledByAdmin()
  1821. // is implemented as a call to VerifyPathControlledByUser, which gives
  1822. // us the ability to test with paths under the test's temp directory,
  1823. // using a user id we control.
  1824. // Pull tests of VerifyPathControlledByUserTest() into a separate test class
  1825. // with a common SetUp() method.
  1826. class VerifyPathControlledByUserTest : public FileUtilTest {
  1827. protected:
  1828. virtual void SetUp() OVERRIDE {
  1829. FileUtilTest::SetUp();
  1830. // Create a basic structure used by each test.
  1831. // base_dir_
  1832. // |-> sub_dir_
  1833. // |-> text_file_
  1834. base_dir_ = temp_dir_.path().AppendASCII("base_dir");
  1835. ASSERT_TRUE(CreateDirectory(base_dir_));
  1836. sub_dir_ = base_dir_.AppendASCII("sub_dir");
  1837. ASSERT_TRUE(CreateDirectory(sub_dir_));
  1838. text_file_ = sub_dir_.AppendASCII("file.txt");
  1839. CreateTextFile(text_file_, L"This text file has some text in it.");
  1840. // Get the user and group files are created with from |base_dir_|.
  1841. struct stat stat_buf;
  1842. ASSERT_EQ(0, stat(base_dir_.value().c_str(), &stat_buf));
  1843. uid_ = stat_buf.st_uid;
  1844. ok_gids_.insert(stat_buf.st_gid);
  1845. bad_gids_.insert(stat_buf.st_gid + 1);
  1846. ASSERT_EQ(uid_, geteuid()); // This process should be the owner.
  1847. // To ensure that umask settings do not cause the initial state
  1848. // of permissions to be different from what we expect, explicitly
  1849. // set permissions on the directories we create.
  1850. // Make all files and directories non-world-writable.
  1851. // Users and group can read, write, traverse
  1852. int enabled_permissions =
  1853. FILE_PERMISSION_USER_MASK | FILE_PERMISSION_GROUP_MASK;
  1854. // Other users can't read, write, traverse
  1855. int disabled_permissions = FILE_PERMISSION_OTHERS_MASK;
  1856. ASSERT_NO_FATAL_FAILURE(
  1857. ChangePosixFilePermissions(
  1858. base_dir_, enabled_permissions, disabled_permissions));
  1859. ASSERT_NO_FATAL_FAILURE(
  1860. ChangePosixFilePermissions(
  1861. sub_dir_, enabled_permissions, disabled_permissions));
  1862. }
  1863. #if defined(OS_POSIX)
  1864. virtual void TearDown() OVERRIDE {
  1865. FileUtilTest::TearDown();
  1866. }
  1867. #endif
  1868. FilePath base_dir_;
  1869. FilePath sub_dir_;
  1870. FilePath text_file_;
  1871. uid_t uid_;
  1872. std::set<gid_t> ok_gids_;
  1873. std::set<gid_t> bad_gids_;
  1874. };
  1875. TEST_F(VerifyPathControlledByUserTest, BadPaths) {
  1876. // File does not exist.
  1877. FilePath does_not_exist = base_dir_.AppendASCII("does")
  1878. .AppendASCII("not")
  1879. .AppendASCII("exist");
  1880. EXPECT_FALSE(
  1881. butil::VerifyPathControlledByUser(
  1882. base_dir_, does_not_exist, uid_, ok_gids_));
  1883. // |base| not a subpath of |path|.
  1884. EXPECT_FALSE(
  1885. butil::VerifyPathControlledByUser(
  1886. sub_dir_, base_dir_, uid_, ok_gids_));
  1887. // An empty base path will fail to be a prefix for any path.
  1888. FilePath empty;
  1889. EXPECT_FALSE(
  1890. butil::VerifyPathControlledByUser(
  1891. empty, base_dir_, uid_, ok_gids_));
  1892. // Finding that a bad call fails proves nothing unless a good call succeeds.
  1893. EXPECT_TRUE(
  1894. butil::VerifyPathControlledByUser(
  1895. base_dir_, sub_dir_, uid_, ok_gids_));
  1896. }
  1897. TEST_F(VerifyPathControlledByUserTest, Symlinks) {
  1898. // Symlinks in the path should cause failure.
  1899. // Symlink to the file at the end of the path.
  1900. FilePath file_link = base_dir_.AppendASCII("file_link");
  1901. ASSERT_TRUE(CreateSymbolicLink(text_file_, file_link))
  1902. << "Failed to create symlink.";
  1903. EXPECT_FALSE(
  1904. butil::VerifyPathControlledByUser(
  1905. base_dir_, file_link, uid_, ok_gids_));
  1906. EXPECT_FALSE(
  1907. butil::VerifyPathControlledByUser(
  1908. file_link, file_link, uid_, ok_gids_));
  1909. // Symlink from one directory to another within the path.
  1910. FilePath link_to_sub_dir = base_dir_.AppendASCII("link_to_sub_dir");
  1911. ASSERT_TRUE(CreateSymbolicLink(sub_dir_, link_to_sub_dir))
  1912. << "Failed to create symlink.";
  1913. FilePath file_path_with_link = link_to_sub_dir.AppendASCII("file.txt");
  1914. ASSERT_TRUE(PathExists(file_path_with_link));
  1915. EXPECT_FALSE(
  1916. butil::VerifyPathControlledByUser(
  1917. base_dir_, file_path_with_link, uid_, ok_gids_));
  1918. EXPECT_FALSE(
  1919. butil::VerifyPathControlledByUser(
  1920. link_to_sub_dir, file_path_with_link, uid_, ok_gids_));
  1921. // Symlinks in parents of base path are allowed.
  1922. EXPECT_TRUE(
  1923. butil::VerifyPathControlledByUser(
  1924. file_path_with_link, file_path_with_link, uid_, ok_gids_));
  1925. }
  1926. TEST_F(VerifyPathControlledByUserTest, OwnershipChecks) {
  1927. // Get a uid that is not the uid of files we create.
  1928. uid_t bad_uid = uid_ + 1;
  1929. // Make all files and directories non-world-writable.
  1930. ASSERT_NO_FATAL_FAILURE(
  1931. ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
  1932. ASSERT_NO_FATAL_FAILURE(
  1933. ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
  1934. ASSERT_NO_FATAL_FAILURE(
  1935. ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
  1936. // We control these paths.
  1937. EXPECT_TRUE(
  1938. butil::VerifyPathControlledByUser(
  1939. base_dir_, sub_dir_, uid_, ok_gids_));
  1940. EXPECT_TRUE(
  1941. butil::VerifyPathControlledByUser(
  1942. base_dir_, text_file_, uid_, ok_gids_));
  1943. EXPECT_TRUE(
  1944. butil::VerifyPathControlledByUser(
  1945. sub_dir_, text_file_, uid_, ok_gids_));
  1946. // Another user does not control these paths.
  1947. EXPECT_FALSE(
  1948. butil::VerifyPathControlledByUser(
  1949. base_dir_, sub_dir_, bad_uid, ok_gids_));
  1950. EXPECT_FALSE(
  1951. butil::VerifyPathControlledByUser(
  1952. base_dir_, text_file_, bad_uid, ok_gids_));
  1953. EXPECT_FALSE(
  1954. butil::VerifyPathControlledByUser(
  1955. sub_dir_, text_file_, bad_uid, ok_gids_));
  1956. // Another group does not control the paths.
  1957. EXPECT_FALSE(
  1958. butil::VerifyPathControlledByUser(
  1959. base_dir_, sub_dir_, uid_, bad_gids_));
  1960. EXPECT_FALSE(
  1961. butil::VerifyPathControlledByUser(
  1962. base_dir_, text_file_, uid_, bad_gids_));
  1963. EXPECT_FALSE(
  1964. butil::VerifyPathControlledByUser(
  1965. sub_dir_, text_file_, uid_, bad_gids_));
  1966. }
  1967. TEST_F(VerifyPathControlledByUserTest, GroupWriteTest) {
  1968. // Make all files and directories writable only by their owner.
  1969. ASSERT_NO_FATAL_FAILURE(
  1970. ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH|S_IWGRP));
  1971. ASSERT_NO_FATAL_FAILURE(
  1972. ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH|S_IWGRP));
  1973. ASSERT_NO_FATAL_FAILURE(
  1974. ChangePosixFilePermissions(text_file_, 0u, S_IWOTH|S_IWGRP));
  1975. // Any group is okay because the path is not group-writable.
  1976. EXPECT_TRUE(
  1977. butil::VerifyPathControlledByUser(
  1978. base_dir_, sub_dir_, uid_, ok_gids_));
  1979. EXPECT_TRUE(
  1980. butil::VerifyPathControlledByUser(
  1981. base_dir_, text_file_, uid_, ok_gids_));
  1982. EXPECT_TRUE(
  1983. butil::VerifyPathControlledByUser(
  1984. sub_dir_, text_file_, uid_, ok_gids_));
  1985. EXPECT_TRUE(
  1986. butil::VerifyPathControlledByUser(
  1987. base_dir_, sub_dir_, uid_, bad_gids_));
  1988. EXPECT_TRUE(
  1989. butil::VerifyPathControlledByUser(
  1990. base_dir_, text_file_, uid_, bad_gids_));
  1991. EXPECT_TRUE(
  1992. butil::VerifyPathControlledByUser(
  1993. sub_dir_, text_file_, uid_, bad_gids_));
  1994. // No group is okay, because we don't check the group
  1995. // if no group can write.
  1996. std::set<gid_t> no_gids; // Empty set of gids.
  1997. EXPECT_TRUE(
  1998. butil::VerifyPathControlledByUser(
  1999. base_dir_, sub_dir_, uid_, no_gids));
  2000. EXPECT_TRUE(
  2001. butil::VerifyPathControlledByUser(
  2002. base_dir_, text_file_, uid_, no_gids));
  2003. EXPECT_TRUE(
  2004. butil::VerifyPathControlledByUser(
  2005. sub_dir_, text_file_, uid_, no_gids));
  2006. // Make all files and directories writable by their group.
  2007. ASSERT_NO_FATAL_FAILURE(
  2008. ChangePosixFilePermissions(base_dir_, S_IWGRP, 0u));
  2009. ASSERT_NO_FATAL_FAILURE(
  2010. ChangePosixFilePermissions(sub_dir_, S_IWGRP, 0u));
  2011. ASSERT_NO_FATAL_FAILURE(
  2012. ChangePosixFilePermissions(text_file_, S_IWGRP, 0u));
  2013. // Now |ok_gids_| works, but |bad_gids_| fails.
  2014. EXPECT_TRUE(
  2015. butil::VerifyPathControlledByUser(
  2016. base_dir_, sub_dir_, uid_, ok_gids_));
  2017. EXPECT_TRUE(
  2018. butil::VerifyPathControlledByUser(
  2019. base_dir_, text_file_, uid_, ok_gids_));
  2020. EXPECT_TRUE(
  2021. butil::VerifyPathControlledByUser(
  2022. sub_dir_, text_file_, uid_, ok_gids_));
  2023. EXPECT_FALSE(
  2024. butil::VerifyPathControlledByUser(
  2025. base_dir_, sub_dir_, uid_, bad_gids_));
  2026. EXPECT_FALSE(
  2027. butil::VerifyPathControlledByUser(
  2028. base_dir_, text_file_, uid_, bad_gids_));
  2029. EXPECT_FALSE(
  2030. butil::VerifyPathControlledByUser(
  2031. sub_dir_, text_file_, uid_, bad_gids_));
  2032. // Because any group in the group set is allowed,
  2033. // the union of good and bad gids passes.
  2034. std::set<gid_t> multiple_gids;
  2035. std::set_union(
  2036. ok_gids_.begin(), ok_gids_.end(),
  2037. bad_gids_.begin(), bad_gids_.end(),
  2038. std::inserter(multiple_gids, multiple_gids.begin()));
  2039. EXPECT_TRUE(
  2040. butil::VerifyPathControlledByUser(
  2041. base_dir_, sub_dir_, uid_, multiple_gids));
  2042. EXPECT_TRUE(
  2043. butil::VerifyPathControlledByUser(
  2044. base_dir_, text_file_, uid_, multiple_gids));
  2045. EXPECT_TRUE(
  2046. butil::VerifyPathControlledByUser(
  2047. sub_dir_, text_file_, uid_, multiple_gids));
  2048. }
  2049. TEST_F(VerifyPathControlledByUserTest, WriteBitChecks) {
  2050. // Make all files and directories non-world-writable.
  2051. ASSERT_NO_FATAL_FAILURE(
  2052. ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
  2053. ASSERT_NO_FATAL_FAILURE(
  2054. ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
  2055. ASSERT_NO_FATAL_FAILURE(
  2056. ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
  2057. // Initialy, we control all parts of the path.
  2058. EXPECT_TRUE(
  2059. butil::VerifyPathControlledByUser(
  2060. base_dir_, sub_dir_, uid_, ok_gids_));
  2061. EXPECT_TRUE(
  2062. butil::VerifyPathControlledByUser(
  2063. base_dir_, text_file_, uid_, ok_gids_));
  2064. EXPECT_TRUE(
  2065. butil::VerifyPathControlledByUser(
  2066. sub_dir_, text_file_, uid_, ok_gids_));
  2067. // Make base_dir_ world-writable.
  2068. ASSERT_NO_FATAL_FAILURE(
  2069. ChangePosixFilePermissions(base_dir_, S_IWOTH, 0u));
  2070. EXPECT_FALSE(
  2071. butil::VerifyPathControlledByUser(
  2072. base_dir_, sub_dir_, uid_, ok_gids_));
  2073. EXPECT_FALSE(
  2074. butil::VerifyPathControlledByUser(
  2075. base_dir_, text_file_, uid_, ok_gids_));
  2076. EXPECT_TRUE(
  2077. butil::VerifyPathControlledByUser(
  2078. sub_dir_, text_file_, uid_, ok_gids_));
  2079. // Make sub_dir_ world writable.
  2080. ASSERT_NO_FATAL_FAILURE(
  2081. ChangePosixFilePermissions(sub_dir_, S_IWOTH, 0u));
  2082. EXPECT_FALSE(
  2083. butil::VerifyPathControlledByUser(
  2084. base_dir_, sub_dir_, uid_, ok_gids_));
  2085. EXPECT_FALSE(
  2086. butil::VerifyPathControlledByUser(
  2087. base_dir_, text_file_, uid_, ok_gids_));
  2088. EXPECT_FALSE(
  2089. butil::VerifyPathControlledByUser(
  2090. sub_dir_, text_file_, uid_, ok_gids_));
  2091. // Make text_file_ world writable.
  2092. ASSERT_NO_FATAL_FAILURE(
  2093. ChangePosixFilePermissions(text_file_, S_IWOTH, 0u));
  2094. EXPECT_FALSE(
  2095. butil::VerifyPathControlledByUser(
  2096. base_dir_, sub_dir_, uid_, ok_gids_));
  2097. EXPECT_FALSE(
  2098. butil::VerifyPathControlledByUser(
  2099. base_dir_, text_file_, uid_, ok_gids_));
  2100. EXPECT_FALSE(
  2101. butil::VerifyPathControlledByUser(
  2102. sub_dir_, text_file_, uid_, ok_gids_));
  2103. // Make sub_dir_ non-world writable.
  2104. ASSERT_NO_FATAL_FAILURE(
  2105. ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
  2106. EXPECT_FALSE(
  2107. butil::VerifyPathControlledByUser(
  2108. base_dir_, sub_dir_, uid_, ok_gids_));
  2109. EXPECT_FALSE(
  2110. butil::VerifyPathControlledByUser(
  2111. base_dir_, text_file_, uid_, ok_gids_));
  2112. EXPECT_FALSE(
  2113. butil::VerifyPathControlledByUser(
  2114. sub_dir_, text_file_, uid_, ok_gids_));
  2115. // Make base_dir_ non-world-writable.
  2116. ASSERT_NO_FATAL_FAILURE(
  2117. ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
  2118. EXPECT_TRUE(
  2119. butil::VerifyPathControlledByUser(
  2120. base_dir_, sub_dir_, uid_, ok_gids_));
  2121. EXPECT_FALSE(
  2122. butil::VerifyPathControlledByUser(
  2123. base_dir_, text_file_, uid_, ok_gids_));
  2124. EXPECT_FALSE(
  2125. butil::VerifyPathControlledByUser(
  2126. sub_dir_, text_file_, uid_, ok_gids_));
  2127. // Back to the initial state: Nothing is writable, so every path
  2128. // should pass.
  2129. ASSERT_NO_FATAL_FAILURE(
  2130. ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
  2131. EXPECT_TRUE(
  2132. butil::VerifyPathControlledByUser(
  2133. base_dir_, sub_dir_, uid_, ok_gids_));
  2134. EXPECT_TRUE(
  2135. butil::VerifyPathControlledByUser(
  2136. base_dir_, text_file_, uid_, ok_gids_));
  2137. EXPECT_TRUE(
  2138. butil::VerifyPathControlledByUser(
  2139. sub_dir_, text_file_, uid_, ok_gids_));
  2140. }
  2141. TEST_F(FileUtilTest, CreateDirectoryParentsNotExist) {
  2142. ASSERT_TRUE(butil::CreateDirectory(temp_dir_.path()));
  2143. butil::FilePath creating_dir = temp_dir_.path().Append("sub1").Append("sub2");
  2144. std::cout << "path=" << creating_dir.value() << std::endl;
  2145. ASSERT_FALSE(butil::CreateDirectory(creating_dir, false));
  2146. ASSERT_TRUE(butil::CreateDirectory(creating_dir, true));
  2147. }
  2148. #if defined(OS_ANDROID)
  2149. TEST_F(FileUtilTest, ValidContentUriTest) {
  2150. // Get the test image path.
  2151. FilePath data_dir;
  2152. ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
  2153. data_dir = data_dir.AppendASCII("file_util");
  2154. ASSERT_TRUE(PathExists(data_dir));
  2155. FilePath image_file = data_dir.Append(FILE_PATH_LITERAL("red.png"));
  2156. int64_t image_size;
  2157. GetFileSize(image_file, &image_size);
  2158. EXPECT_LT(0, image_size);
  2159. // Insert the image into MediaStore. MediaStore will do some conversions, and
  2160. // return the content URI.
  2161. FilePath path = file_util::InsertImageIntoMediaStore(image_file);
  2162. EXPECT_TRUE(path.IsContentUri());
  2163. EXPECT_TRUE(PathExists(path));
  2164. // The file size may not equal to the input image as MediaStore may convert
  2165. // the image.
  2166. int64_t content_uri_size;
  2167. GetFileSize(path, &content_uri_size);
  2168. EXPECT_EQ(image_size, content_uri_size);
  2169. // We should be able to read the file.
  2170. char* buffer = new char[image_size];
  2171. File file = OpenContentUriForRead(path);
  2172. EXPECT_TRUE(file.IsValid());
  2173. EXPECT_TRUE(file.ReadAtCurrentPos(buffer, image_size));
  2174. delete[] buffer;
  2175. }
  2176. TEST_F(FileUtilTest, NonExistentContentUriTest) {
  2177. FilePath path("content://foo.bar");
  2178. EXPECT_TRUE(path.IsContentUri());
  2179. EXPECT_FALSE(PathExists(path));
  2180. // Size should be smaller than 0.
  2181. int64_t size;
  2182. EXPECT_FALSE(GetFileSize(path, &size));
  2183. // We should not be able to read the file.
  2184. File file = OpenContentUriForRead(path);
  2185. EXPECT_FALSE(file.IsValid());
  2186. }
  2187. #endif
  2188. TEST(ScopedFD, ScopedFDDoesClose) {
  2189. int fds[2];
  2190. char c = 0;
  2191. ASSERT_EQ(0, pipe(fds));
  2192. const int write_end = fds[1];
  2193. butil::ScopedFD read_end_closer(fds[0]);
  2194. {
  2195. butil::ScopedFD write_end_closer(fds[1]);
  2196. }
  2197. // This is the only thread. This file descriptor should no longer be valid.
  2198. int ret = close(write_end);
  2199. EXPECT_EQ(-1, ret);
  2200. EXPECT_EQ(EBADF, errno);
  2201. // Make sure read(2) won't block.
  2202. ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
  2203. // Reading the pipe should EOF.
  2204. EXPECT_EQ(0, read(fds[0], &c, 1));
  2205. }
  2206. #if defined(GTEST_HAS_DEATH_TEST)
  2207. void CloseWithScopedFD(int fd) {
  2208. butil::ScopedFD fd_closer(fd);
  2209. }
  2210. #endif
  2211. TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
  2212. int fds[2];
  2213. ASSERT_EQ(0, pipe(fds));
  2214. butil::ScopedFD read_end_closer(fds[0]);
  2215. EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
  2216. #if defined(GTEST_HAS_DEATH_TEST)
  2217. // This is the only thread. This file descriptor should no longer be valid.
  2218. // Trying to close it should crash. This is important for security.
  2219. EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
  2220. #endif
  2221. }
  2222. #endif // defined(OS_POSIX)
  2223. } // namespace
  2224. } // namespace butil