fileAPI.cpp 29 KB

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