fileAPI.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2020 to 2022 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. // Include fileAPI without falling back on local syntax implicitly.
  24. // This prevents any local syntax from being implied in functions that are supposed to use variable pathSyntax.
  25. #define NO_IMPLICIT_PATH_SYNTAX
  26. #include "fileAPI.h"
  27. #ifdef USE_MICROSOFT_WINDOWS
  28. // Headers for MS-Windows
  29. #include <windows.h>
  30. #include <synchapi.h>
  31. #else
  32. // Headers for Posix compliant systems.
  33. #include <unistd.h>
  34. #include <spawn.h>
  35. #include <sys/wait.h>
  36. #include <sys/stat.h>
  37. #include <dirent.h>
  38. // The environment flags contain information such as username, language, color settings, which system shell and window manager is used...
  39. extern char **environ;
  40. #endif
  41. #include <fstream>
  42. #include <cstdlib>
  43. #include "bufferAPI.h"
  44. #include "../base/virtualStack.h"
  45. namespace dsr {
  46. constexpr const char32_t* getPathSeparator(PathSyntax pathSyntax) {
  47. if (pathSyntax == PathSyntax::Windows) {
  48. return U"\\";
  49. } else if (pathSyntax == PathSyntax::Posix) {
  50. return U"/";
  51. } else {
  52. return U"?";
  53. }
  54. }
  55. #ifdef USE_MICROSOFT_WINDOWS
  56. using NativeChar = wchar_t; // UTF-16
  57. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF16LE;
  58. #define FILE_ACCESS_FUNCTION _wfopen
  59. #define FILE_ACCESS_SELECTION (write ? L"wb" : L"rb")
  60. List<String> file_impl_getInputArguments() {
  61. // Get a pointer to static memory with the command
  62. LPWSTR cmd = GetCommandLineW();
  63. // Split the arguments into an array of arguments
  64. int argc = 0;
  65. LPWSTR *argv = CommandLineToArgvW(cmd, &argc);
  66. // Convert the arguments into dsr::List<dsr::String>
  67. List<String> args = file_impl_convertInputArguments(argc, (void**)argv);
  68. // Free the native list of arguments
  69. LocalFree(argv);
  70. return args;
  71. }
  72. #else
  73. using NativeChar = char; // UTF-8
  74. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF8;
  75. #define FILE_ACCESS_FUNCTION fopen
  76. #define FILE_ACCESS_SELECTION (write ? "wb" : "rb")
  77. List<String> file_impl_getInputArguments() { return List<String>(); }
  78. #endif
  79. // Length of fixed size buffers.
  80. const int maxLength = 512;
  81. static const NativeChar* toNativeString(const ReadableString &filename, Buffer &buffer) {
  82. buffer = string_saveToMemory(filename, nativeEncoding, LineEncoding::CrLf, false, true);
  83. return (const NativeChar*)buffer_dangerous_getUnsafeData(buffer);
  84. }
  85. static String fromNativeString(const NativeChar *text) {
  86. return string_dangerous_decodeFromData(text, nativeEncoding);
  87. }
  88. List<String> file_impl_convertInputArguments(int argn, void **argv) {
  89. List<String> result;
  90. result.reserve(argn);
  91. for (int a = 0; a < argn; a++) {
  92. result.push(fromNativeString((NativeChar*)(argv[a])));
  93. }
  94. return result;
  95. }
  96. static FILE* accessFile(const ReadableString &filename, bool write) {
  97. Buffer buffer;
  98. return FILE_ACCESS_FUNCTION(toNativeString(filename, buffer), FILE_ACCESS_SELECTION);
  99. }
  100. Buffer file_loadBuffer(const ReadableString& filename, bool mustExist) {
  101. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  102. FILE *file = accessFile(modifiedFilename, false);
  103. if (file != nullptr) {
  104. // Get the file's size by going to the end, measuring, and going back
  105. fseek(file, 0L, SEEK_END);
  106. int64_t fileSize = ftell(file);
  107. rewind(file);
  108. // Allocate a buffer of the file's size
  109. Buffer buffer = buffer_create(fileSize);
  110. fread((void*)buffer_dangerous_getUnsafeData(buffer), fileSize, 1, file);
  111. fclose(file);
  112. return buffer;
  113. } else {
  114. if (mustExist) {
  115. throwError(U"Failed to load ", modifiedFilename, ".\n");
  116. }
  117. // If the file cound not be found and opened, an empty buffer is returned
  118. return Buffer();
  119. }
  120. }
  121. bool file_saveBuffer(const ReadableString& filename, Buffer buffer, bool mustWork) {
  122. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  123. if (!buffer_exists(buffer)) {
  124. if (mustWork) {
  125. throwError(U"buffer_save: Can't save a buffer that don't exist to a file.\n");
  126. }
  127. return false;
  128. } else {
  129. FILE *file = accessFile(modifiedFilename, true);
  130. if (file != nullptr) {
  131. fwrite((void*)buffer_dangerous_getUnsafeData(buffer), buffer_getSize(buffer), 1, file);
  132. fclose(file);
  133. } else {
  134. if (mustWork) {
  135. throwError("Failed to save ", modifiedFilename, ".\n");
  136. }
  137. return false;
  138. }
  139. }
  140. // Success if there are no errors.
  141. return true;
  142. }
  143. const char32_t* file_separator() {
  144. return getPathSeparator(LOCAL_PATH_SYNTAX);
  145. }
  146. bool file_isSeparator(DsrChar c) {
  147. return c == U'\\' || c == U'/';
  148. }
  149. // Returns the index of the first / or \ in path, or defaultIndex if none existed.
  150. int64_t file_findFirstSeparator(const ReadableString &path, int64_t defaultIndex, int64_t startIndex) {
  151. for (int64_t i = startIndex; i < string_length(path); i++) {
  152. DsrChar c = path[i];
  153. if (file_isSeparator(c)) {
  154. return i;
  155. }
  156. }
  157. return defaultIndex;
  158. }
  159. // Returns the index of the last / or \ in path, or defaultIndex if none existed.
  160. int64_t file_findLastSeparator(const ReadableString &path, int64_t defaultIndex) {
  161. for (int64_t i = string_length(path) - 1; i >= 0; i--) {
  162. DsrChar c = path[i];
  163. if (file_isSeparator(c)) {
  164. return i;
  165. }
  166. }
  167. return defaultIndex;
  168. }
  169. String file_optimizePath(const ReadableString &path, PathSyntax pathSyntax) {
  170. String result; // The final output being appended.
  171. String currentEntry; // The current entry.
  172. bool hadSeparator = false;
  173. bool hadContent = false;
  174. int64_t inputLength = string_length(path);
  175. string_reserve(result, inputLength);
  176. // Read null terminator from one element outside of the path to allow concluding an entry not followed by any separator.
  177. // The null terminator is not actually stored, but reading out of bound gives a null terminator.
  178. for (int64_t i = 0; i <= inputLength; i++) {
  179. DsrChar c = path[i];
  180. bool separator = file_isSeparator(c);
  181. if (separator || i == inputLength) {
  182. bool appendEntry = true;
  183. bool appendSeparator = separator;
  184. if (hadSeparator) {
  185. if (hadContent && string_length(currentEntry) == 0) {
  186. // Reduce non-leading // into / by skipping "" entries.
  187. // Any leading multiples of slashes have their count preserved, because some systems use them to indicate special use cases.
  188. appendEntry = false;
  189. appendSeparator = false;
  190. } else if (string_match(currentEntry, U".")) {
  191. // Reduce /./ into / by skipping "." entries.
  192. appendEntry = false;
  193. appendSeparator = false;
  194. } else if (string_match(currentEntry, U"..")) {
  195. // Reduce the parent directory against the reverse ".." entry.
  196. result = file_getRelativeParentFolder(result, pathSyntax);
  197. if (string_match(result, U"?")) {
  198. return U"?";
  199. }
  200. appendEntry = false;
  201. }
  202. }
  203. if (appendEntry) {
  204. string_append(result, string_removeOuterWhiteSpace(currentEntry));
  205. }
  206. if (appendSeparator) {
  207. string_append(result, getPathSeparator(pathSyntax));
  208. }
  209. currentEntry = U"";
  210. if (separator) {
  211. hadSeparator = true;
  212. }
  213. } else {
  214. string_appendChar(currentEntry, c);
  215. hadContent = true;
  216. }
  217. }
  218. // Remove trailing separators if we had content.
  219. if (hadSeparator && hadContent) {
  220. int64_t lastNonSeparator = -1;
  221. for (int64_t i = string_length(result) - 1; i >= 0; i--) {
  222. if (!file_isSeparator(result[i])) {
  223. lastNonSeparator = i;
  224. break;
  225. }
  226. }
  227. result = string_until(result, lastNonSeparator);
  228. }
  229. return result;
  230. }
  231. ReadableString file_getPathlessName(const ReadableString &path) {
  232. return string_after(path, file_findLastSeparator(path));
  233. }
  234. bool file_hasExtension(const String& path) {
  235. int64_t lastDotIndex = string_findLast(path, U'.');
  236. int64_t lastSeparatorIndex = file_findLastSeparator(path);
  237. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  238. return true;
  239. } else {
  240. return false;
  241. }
  242. }
  243. ReadableString file_getExtension(const String& filename) {
  244. int64_t lastDotIndex = string_findLast(filename, U'.');
  245. int64_t lastSeparatorIndex = file_findLastSeparator(filename);
  246. // Only use the last dot if there is no folder separator after it.
  247. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  248. return string_removeOuterWhiteSpace(string_after(filename, lastDotIndex));
  249. } else {
  250. return U"";
  251. }
  252. }
  253. ReadableString file_getExtensionless(const String& filename) {
  254. int64_t lastDotIndex = string_findLast(filename, U'.');
  255. int64_t lastSeparatorIndex = file_findLastSeparator(filename);
  256. // Only use the last dot if there is no folder separator after it.
  257. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  258. return string_removeOuterWhiteSpace(string_before(filename, lastDotIndex));
  259. } else {
  260. return string_removeOuterWhiteSpace(filename);
  261. }
  262. }
  263. String file_getRelativeParentFolder(const ReadableString &path, PathSyntax pathSyntax) {
  264. String optimizedPath = file_optimizePath(path, pathSyntax);
  265. if (string_length(optimizedPath) == 0) {
  266. // Use .. to go outside of the current directory.
  267. return U"..";
  268. } else if (string_match(file_getPathlessName(optimizedPath), U"?")) {
  269. // From unknown to unknown.
  270. return U"?";
  271. } else if (file_isRoot(optimizedPath, false, pathSyntax)) {
  272. // If it's the known true root, then we know that it does not have a parent and must fail.
  273. return U"?";
  274. } else if (file_isRoot(optimizedPath, true, pathSyntax)) {
  275. // If it's an alias for an arbitrary folder, use .. to leave it.
  276. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  277. } else if (string_match(file_getPathlessName(optimizedPath), U"..")) {
  278. // Add more dots to the path.
  279. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  280. } else {
  281. // Inside of something.
  282. int64_t lastSeparator = file_findLastSeparator(optimizedPath, 0);
  283. if (pathSyntax == PathSyntax::Windows) {
  284. // Return everything before the last separator.
  285. return string_before(optimizedPath, lastSeparator);
  286. } else { // PathSyntax::Posix
  287. if (file_hasRoot(path, false, pathSyntax) && lastSeparator == 0) {
  288. // Keep the absolute root.
  289. return U"/";
  290. } else {
  291. // Keep everything before the last separator.
  292. return string_before(optimizedPath, lastSeparator);
  293. }
  294. }
  295. }
  296. }
  297. String file_getTheoreticalAbsoluteParentFolder(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  298. if (file_hasRoot(path, true, LOCAL_PATH_SYNTAX)) {
  299. // Absolute paths should be treated the same as a theoretical path.
  300. return file_getRelativeParentFolder(path, pathSyntax);
  301. } else {
  302. // If the input is not absolute, convert it before taking the parent directory.
  303. return file_getRelativeParentFolder(file_getTheoreticalAbsolutePath(path, currentPath, pathSyntax), pathSyntax);
  304. }
  305. }
  306. String file_getAbsoluteParentFolder(const ReadableString &path) {
  307. return file_getTheoreticalAbsoluteParentFolder(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  308. }
  309. bool file_isRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  310. ReadableString cleanPath = string_removeOuterWhiteSpace(path);
  311. int64_t length = string_length(cleanPath);
  312. if (length == 0) {
  313. // Relative path is not a root.
  314. return false;
  315. } else if (length == 1) {
  316. DsrChar c = cleanPath[0];
  317. if (pathSyntax == PathSyntax::Windows) {
  318. return c == U'\\'; // Implicit drive root.
  319. } else { // PathSyntax::Posix
  320. return c == U'/' || (c == U'~' && treatHomeFolderAsRoot); // Root over all drives or home folder.
  321. }
  322. } else {
  323. if (pathSyntax == PathSyntax::Windows && cleanPath[length - 1] == U':') {
  324. // C:, D:, ...
  325. return true;
  326. } else {
  327. return false;
  328. }
  329. }
  330. }
  331. bool file_hasRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  332. int64_t firstSeparator = file_findFirstSeparator(path);
  333. if (firstSeparator == -1) {
  334. // If there is no separator, path has a root if it is a root.
  335. return file_isRoot(path, treatHomeFolderAsRoot, pathSyntax);
  336. } else if (firstSeparator == 0) {
  337. // Starting with a separator. Either an implicit drive on Windows or the whole system's root on Posix.
  338. return true;
  339. } else {
  340. // Has a root if the first entry before the first slash is a root.
  341. return file_isRoot(string_before(path, firstSeparator), treatHomeFolderAsRoot, pathSyntax);
  342. }
  343. }
  344. bool file_setCurrentPath(const ReadableString &path) {
  345. Buffer buffer;
  346. const NativeChar *nativePath = toNativeString(file_optimizePath(path, LOCAL_PATH_SYNTAX), buffer);
  347. #ifdef USE_MICROSOFT_WINDOWS
  348. return SetCurrentDirectoryW(nativePath) != 0;
  349. #else
  350. return chdir(nativePath) == 0;
  351. #endif
  352. }
  353. String file_getCurrentPath() {
  354. #ifdef USE_MICROSOFT_WINDOWS
  355. NativeChar resultBuffer[maxLength + 1] = {0};
  356. GetCurrentDirectoryW(maxLength, resultBuffer);
  357. return fromNativeString(resultBuffer);
  358. #else
  359. NativeChar resultBuffer[maxLength + 1] = {0};
  360. getcwd(resultBuffer, maxLength);
  361. return fromNativeString(resultBuffer);
  362. #endif
  363. }
  364. String file_followSymbolicLink(const ReadableString &path, bool mustExist) {
  365. #ifdef USE_MICROSOFT_WINDOWS
  366. // TODO: Is there anything that can be used as a symbolic link on Windows?
  367. #else
  368. String modifiedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  369. Buffer buffer;
  370. const NativeChar *nativePath = toNativeString(modifiedPath, buffer);
  371. NativeChar resultBuffer[maxLength + 1] = {0};
  372. if (readlink(nativePath, resultBuffer, maxLength) != -1) {
  373. return fromNativeString(resultBuffer);
  374. }
  375. #endif
  376. if (mustExist) { throwError(U"The symbolic link ", path, " could not be found!\n"); }
  377. return U"?";
  378. }
  379. String file_getApplicationFolder(bool allowFallback) {
  380. #ifdef USE_MICROSOFT_WINDOWS
  381. NativeChar resultBuffer[maxLength + 1] = {0};
  382. GetModuleFileNameW(nullptr, resultBuffer, maxLength);
  383. return file_getRelativeParentFolder(fromNativeString(resultBuffer), LOCAL_PATH_SYNTAX);
  384. #else
  385. NativeChar resultBuffer[maxLength + 1] = {0};
  386. if (readlink("/proc/self/exe", resultBuffer, maxLength) != -1) {
  387. // Linux detected
  388. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  389. } else if (readlink("/proc/curproc/file", resultBuffer, maxLength) != -1) {
  390. // BSD detected
  391. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  392. } else if (readlink("/proc/self/path/a.out", resultBuffer, maxLength) != -1) {
  393. // Solaris detected
  394. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  395. } else if (allowFallback) {
  396. return file_getCurrentPath();
  397. } else {
  398. throwError("file_getApplicationFolder is not implemented for the current system!\n");
  399. return U"";
  400. }
  401. #endif
  402. }
  403. String file_combinePaths(const ReadableString &a, const ReadableString &b, PathSyntax pathSyntax) {
  404. ReadableString cleanA = string_removeOuterWhiteSpace(a);
  405. ReadableString cleanB = string_removeOuterWhiteSpace(b);
  406. int64_t lengthA = string_length(cleanA);
  407. int64_t lengthB = string_length(cleanB);
  408. if (file_hasRoot(b, true, pathSyntax)) {
  409. // Restarting from root or home folder.
  410. return cleanB;
  411. } else if (lengthA == 0) {
  412. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  413. return cleanB;
  414. } else if (lengthB == 0) {
  415. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  416. return cleanA;
  417. } else {
  418. if (file_isSeparator(a[lengthA - 1])) {
  419. // Already ending with a separator.
  420. return string_combine(cleanA, cleanB);
  421. } else {
  422. // Combine using a separator.
  423. return string_combine(cleanA, getPathSeparator(pathSyntax), cleanB);
  424. }
  425. }
  426. }
  427. // Returns path with the drive letter applied from currentPath if missing in path.
  428. // Used for converting drive relative paths into true absolute paths on MS-Windows.
  429. static String applyDriveLetter(const ReadableString &path, const ReadableString &currentPath) {
  430. // Convert implicit drive into a named drive.
  431. if (path[0] == U'\\') {
  432. int64_t colonIndex = string_findFirst(currentPath, U':', -1);
  433. if (colonIndex == -1) {
  434. return U"?";
  435. } else {
  436. // Get the drive letter from the current path.
  437. String drive = string_until(currentPath, colonIndex);
  438. return string_combine(drive, path);
  439. }
  440. } else {
  441. // Already absolute.
  442. return path;
  443. }
  444. }
  445. String file_getTheoreticalAbsolutePath(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  446. // Home folders are absolute enough, because we don't want to lose the account ambiguity by mangling it into hardcoded usernames.
  447. if (file_hasRoot(path, true, pathSyntax)) {
  448. if (pathSyntax == PathSyntax::Windows) {
  449. // Make sure that no drive letter is missing.
  450. return applyDriveLetter(file_optimizePath(path, pathSyntax), currentPath);
  451. } else {
  452. // Already absolute.
  453. return file_optimizePath(path, pathSyntax);
  454. }
  455. } else {
  456. // Convert from relative path.
  457. return file_optimizePath(file_combinePaths(currentPath, path, pathSyntax), pathSyntax);
  458. }
  459. }
  460. String file_getAbsolutePath(const ReadableString &path) {
  461. return file_getTheoreticalAbsolutePath(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  462. }
  463. int64_t file_getFileSize(const ReadableString& filename) {
  464. int64_t result = -1;
  465. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  466. Buffer buffer;
  467. const NativeChar *nativePath = toNativeString(modifiedFilename, buffer);
  468. #ifdef USE_MICROSOFT_WINDOWS
  469. LARGE_INTEGER fileSize;
  470. HANDLE fileHandle = CreateFileW(nativePath, 0, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  471. if (fileHandle != INVALID_HANDLE_VALUE) {
  472. if (GetFileSizeEx(fileHandle, &fileSize)) {
  473. result = fileSize.QuadPart;
  474. }
  475. CloseHandle(fileHandle);
  476. }
  477. #else
  478. struct stat info;
  479. if (stat(nativePath, &info) == 0) {
  480. result = info.st_size;
  481. }
  482. #endif
  483. return result;
  484. }
  485. String& string_toStreamIndented(String& target, const EntryType& source, const ReadableString& indentation) {
  486. string_append(target, indentation);
  487. if (source == EntryType::NotFound) {
  488. string_append(target, U"not found");
  489. } else if (source == EntryType::File) {
  490. string_append(target, U"a file");
  491. } else if (source == EntryType::Folder) {
  492. string_append(target, U"a folder");
  493. } else if (source == EntryType::SymbolicLink) {
  494. string_append(target, U"a symbolic link");
  495. } else {
  496. string_append(target, U"unhandled");
  497. }
  498. return target;
  499. }
  500. EntryType file_getEntryType(const ReadableString &path) {
  501. EntryType result = EntryType::NotFound;
  502. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  503. Buffer buffer;
  504. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  505. #ifdef USE_MICROSOFT_WINDOWS
  506. DWORD dwAttrib = GetFileAttributesW(nativePath);
  507. if (dwAttrib != INVALID_FILE_ATTRIBUTES) {
  508. if (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) {
  509. result = EntryType::Folder;
  510. } else {
  511. result = EntryType::File;
  512. }
  513. }
  514. #else
  515. struct stat info;
  516. int errorCode = stat(nativePath, &info);
  517. if (errorCode == 0) {
  518. if (S_ISDIR(info.st_mode)) {
  519. result = EntryType::Folder;
  520. } else if (S_ISREG(info.st_mode)) {
  521. result = EntryType::File;
  522. } else if (S_ISLNK(info.st_mode)) {
  523. result = EntryType::SymbolicLink;
  524. } else {
  525. result = EntryType::UnhandledType;
  526. }
  527. }
  528. #endif
  529. return result;
  530. }
  531. bool file_getFolderContent(const ReadableString& folderPath, std::function<void(const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType)> action) {
  532. String optimizedPath = file_optimizePath(folderPath, LOCAL_PATH_SYNTAX);
  533. #ifdef USE_MICROSOFT_WINDOWS
  534. String pattern = file_combinePaths(optimizedPath, U"*.*", LOCAL_PATH_SYNTAX);
  535. Buffer buffer;
  536. const NativeChar *nativePattern = toNativeString(pattern, buffer);
  537. WIN32_FIND_DATAW findData;
  538. HANDLE findHandle = FindFirstFileW(nativePattern, &findData);
  539. if (findHandle == INVALID_HANDLE_VALUE) {
  540. return false;
  541. } else {
  542. while (true) {
  543. String entryName = fromNativeString(findData.cFileName);
  544. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  545. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  546. EntryType entryType = EntryType::UnhandledType;
  547. if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  548. entryType = EntryType::Folder;
  549. } else {
  550. entryType = EntryType::File;
  551. }
  552. action(entryPath, entryName, entryType);
  553. }
  554. if (!FindNextFileW(findHandle, &findData)) { break; }
  555. }
  556. FindClose(findHandle);
  557. }
  558. #else
  559. Buffer buffer;
  560. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  561. DIR *directory = opendir(nativePath);
  562. if (directory == nullptr) {
  563. return false;
  564. } else {
  565. while (true) {
  566. dirent *entry = readdir(directory);
  567. if (entry != nullptr) {
  568. String entryName = fromNativeString(entry->d_name);
  569. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  570. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  571. EntryType entryType = file_getEntryType(entryPath);
  572. action(entryPath, entryName, entryType);
  573. }
  574. } else {
  575. break;
  576. }
  577. }
  578. }
  579. closedir(directory);
  580. #endif
  581. return true;
  582. }
  583. void file_getPathEntries(const ReadableString& path, std::function<void(ReadableString, int64_t, int64_t)> action) {
  584. int64_t sectionStart = 0;
  585. int64_t length = string_length(path);
  586. for (int64_t i = 0; i < string_length(path); i++) {
  587. DsrChar c = path[i];
  588. if (file_isSeparator(c)) {
  589. int64_t sectionEnd = i - 1; // Inclusive end
  590. ReadableString content = string_inclusiveRange(path, sectionStart, sectionEnd);
  591. if (string_length(content)) { action(content, sectionStart, sectionEnd); }
  592. sectionStart = i + 1;
  593. }
  594. }
  595. if (length > sectionStart) {
  596. int64_t sectionEnd = length - 1; // Inclusive end
  597. ReadableString content = string_inclusiveRange(path, sectionStart, sectionEnd);
  598. if (string_length(content)) { action(content, sectionStart, sectionEnd); }
  599. }
  600. }
  601. bool file_createFolder(const ReadableString &path) {
  602. bool result = false;
  603. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  604. Buffer buffer;
  605. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  606. #ifdef USE_MICROSOFT_WINDOWS
  607. // Create folder with permissions inherited.
  608. result = (CreateDirectoryW(nativePath, nullptr) != 0);
  609. #else
  610. // Create folder with default permissions. Read, write and search for owner and group. Read and search for others.
  611. result = (mkdir(nativePath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
  612. #endif
  613. return result;
  614. }
  615. bool file_removeEmptyFolder(const ReadableString& path) {
  616. bool result = false;
  617. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  618. Buffer buffer;
  619. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  620. // Remove the empty folder.
  621. #ifdef USE_MICROSOFT_WINDOWS
  622. result = (RemoveDirectoryW(nativePath) != 0);
  623. #else
  624. result = (rmdir(nativePath) == 0);
  625. #endif
  626. return result;
  627. }
  628. bool file_removeFile(const ReadableString& filename) {
  629. bool result = false;
  630. String optimizedPath = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  631. Buffer buffer;
  632. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  633. // Remove the empty folder.
  634. #ifdef USE_MICROSOFT_WINDOWS
  635. result = (DeleteFileW(nativePath) != 0);
  636. #else
  637. result = (unlink(nativePath) == 0);
  638. #endif
  639. return result;
  640. }
  641. // DsrProcess is a reference counted pointer to DsrProcessImpl where the last retrieved status still remains for all to read.
  642. // Because aliasing with multiple users of the same pid would deplete the messages in advance.
  643. struct DsrProcessImpl {
  644. // Once the process has already terminated, process_getStatus will only return lastStatus.
  645. bool terminated = false;
  646. // We can assume that a newly created process is running until we are told that it terminated or crashed,
  647. // because DsrProcessImpl would not be created unless launching the application was successful.
  648. DsrProcessStatus lastStatus = DsrProcessStatus::Running;
  649. #ifdef USE_MICROSOFT_WINDOWS
  650. PROCESS_INFORMATION processInfo;
  651. DsrProcessImpl(const PROCESS_INFORMATION &processInfo)
  652. : processInfo(processInfo) {}
  653. ~DsrProcessImpl() {
  654. CloseHandle(processInfo.hProcess);
  655. CloseHandle(processInfo.hThread);
  656. }
  657. #else
  658. pid_t pid;
  659. DsrProcessImpl(pid_t pid) : pid(pid) {}
  660. #endif
  661. };
  662. DsrProcessStatus process_getStatus(const DsrProcess &process) {
  663. if (process.isNull()) {
  664. return DsrProcessStatus::NotStarted;
  665. } else {
  666. if (!process->terminated) {
  667. #ifdef USE_MICROSOFT_WINDOWS
  668. DWORD status = WaitForSingleObject(process->processInfo.hProcess, 0);
  669. if (status == WAIT_OBJECT_0) {
  670. DWORD processResult;
  671. GetExitCodeProcess(process->processInfo.hProcess, &processResult);
  672. process->lastStatus = (processResult == 0) ? DsrProcessStatus::Completed : DsrProcessStatus::Crashed;
  673. process->terminated = true;
  674. }
  675. #else
  676. // When using WNOHANG, waitpid returns zero when the program is still running, and the child pid if it terminated.
  677. int status = 0;
  678. if (waitpid(process->pid, &status, WNOHANG) != 0) {
  679. if (WIFEXITED(status)) {
  680. if (WEXITSTATUS(status) == 0) {
  681. // The program finished and returned 0 for success.
  682. process->lastStatus = DsrProcessStatus::Completed;
  683. } else {
  684. // The program finished, but returned a non-zero result indicating that something still went wrong.
  685. process->lastStatus = DsrProcessStatus::Crashed;
  686. }
  687. process->terminated = true;
  688. } else if (WIFSIGNALED(status)) {
  689. // The program was stopped due to a hard crash.
  690. process->lastStatus = DsrProcessStatus::Crashed;
  691. process->terminated = true;
  692. }
  693. }
  694. #endif
  695. }
  696. return process->lastStatus;
  697. }
  698. }
  699. DsrProcess process_execute(const ReadableString& programPath, List<String> arguments) {
  700. // Convert the program path into the native format.
  701. String optimizedPath = file_optimizePath(programPath, LOCAL_PATH_SYNTAX);
  702. // Convert
  703. #ifdef USE_MICROSOFT_WINDOWS
  704. DsrChar separator = U' ';
  705. #else
  706. DsrChar separator = U'\0';
  707. #endif
  708. String flattenedArguments;
  709. string_append(flattenedArguments, optimizedPath);
  710. string_appendChar(flattenedArguments, separator);
  711. for (int64_t a = 0; a < arguments.length(); a++) {
  712. string_append(flattenedArguments, arguments[a]);
  713. string_appendChar(flattenedArguments, separator);
  714. }
  715. Buffer argBuffer;
  716. const NativeChar *nativeArgs = toNativeString(flattenedArguments, argBuffer);
  717. #ifdef USE_MICROSOFT_WINDOWS
  718. STARTUPINFOW startInfo;
  719. PROCESS_INFORMATION processInfo;
  720. memset(&startInfo, 0, sizeof(STARTUPINFO));
  721. memset(&processInfo, 0, sizeof(PROCESS_INFORMATION));
  722. startInfo.cb = sizeof(STARTUPINFO);
  723. if (CreateProcessW(nullptr, (LPWSTR)nativeArgs, nullptr, nullptr, true, 0, nullptr, nullptr, &startInfo, &processInfo)) {
  724. return handle_create<DsrProcessImpl>(processInfo).setName("DSR Process"); // Success
  725. } else {
  726. return DsrProcess(); // Failure
  727. }
  728. #else
  729. Buffer pathBuffer;
  730. const NativeChar *nativePath = toNativeString(optimizedPath, pathBuffer);
  731. int64_t codePoints = buffer_getSize(argBuffer) / sizeof(NativeChar);
  732. // Count arguments.
  733. int argc = arguments.length() + 1;
  734. // Allocate an array of pointers for each argument and a null terminator.
  735. VirtualStackAllocation<const NativeChar *> argv(argc + 1);
  736. // Fill the array with pointers to the native strings.
  737. int64_t startOffset = 0;
  738. int currentArg = 0;
  739. for (int64_t c = 0; c < codePoints && currentArg < argc; c++) {
  740. if (nativeArgs[c] == 0) {
  741. argv[currentArg] = &(nativeArgs[startOffset]);
  742. startOffset = c + 1;
  743. currentArg++;
  744. }
  745. }
  746. argv[currentArg] = nullptr;
  747. pid_t pid = 0;
  748. if (posix_spawn(&pid, nativePath, nullptr, nullptr, (char**)argv.getUnsafe(), environ) == 0) {
  749. return handle_create<DsrProcessImpl>(pid).setName("DSR Process"); // Success
  750. } else {
  751. return DsrProcess(); // Failure
  752. }
  753. #endif
  754. }
  755. }