ls.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/HashMap.h>
  27. #include <AK/NumberFormat.h>
  28. #include <AK/QuickSort.h>
  29. #include <AK/String.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/Utf8View.h>
  32. #include <AK/Vector.h>
  33. #include <LibCore/ArgsParser.h>
  34. #include <LibCore/DateTime.h>
  35. #include <LibCore/DirIterator.h>
  36. #include <LibCore/File.h>
  37. #include <ctype.h>
  38. #include <dirent.h>
  39. #include <errno.h>
  40. #include <fcntl.h>
  41. #include <grp.h>
  42. #include <pwd.h>
  43. #include <stdio.h>
  44. #include <string.h>
  45. #include <sys/ioctl.h>
  46. #include <sys/stat.h>
  47. #include <time.h>
  48. #include <unistd.h>
  49. static int do_file_system_object_long(const char* path);
  50. static int do_file_system_object_short(const char* path);
  51. static bool flag_classify = false;
  52. static bool flag_colorize = false;
  53. static bool flag_long = false;
  54. static bool flag_show_dotfiles = false;
  55. static bool flag_show_almost_all_dotfiles = false;
  56. static bool flag_ignore_backups = false;
  57. static bool flag_list_directories_only = false;
  58. static bool flag_show_inode = false;
  59. static bool flag_print_numeric = false;
  60. static bool flag_hide_group = false;
  61. static bool flag_human_readable = false;
  62. static bool flag_sort_by_timestamp = false;
  63. static bool flag_reverse_sort = false;
  64. static bool flag_disable_hyperlinks = false;
  65. static size_t terminal_rows = 0;
  66. static size_t terminal_columns = 0;
  67. static bool output_is_terminal = false;
  68. static HashMap<uid_t, String> users;
  69. static HashMap<gid_t, String> groups;
  70. int main(int argc, char** argv)
  71. {
  72. if (pledge("stdio rpath tty", nullptr) < 0) {
  73. perror("pledge");
  74. return 1;
  75. }
  76. struct winsize ws;
  77. int rc = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
  78. if (rc == 0) {
  79. terminal_rows = ws.ws_row;
  80. terminal_columns = ws.ws_col;
  81. output_is_terminal = true;
  82. }
  83. if (!isatty(STDOUT_FILENO)) {
  84. flag_disable_hyperlinks = true;
  85. } else {
  86. flag_colorize = true;
  87. }
  88. if (pledge("stdio rpath", nullptr) < 0) {
  89. perror("pledge");
  90. return 1;
  91. }
  92. Vector<const char*> paths;
  93. Core::ArgsParser args_parser;
  94. args_parser.set_general_help("List files in a directory.");
  95. args_parser.add_option(flag_show_dotfiles, "Show dotfiles", "all", 'a');
  96. args_parser.add_option(flag_show_almost_all_dotfiles, "Do not list implied . and .. directories", nullptr, 'A');
  97. args_parser.add_option(flag_ignore_backups, "Do not list implied entries ending with ~", "--ignore-backups", 'B');
  98. args_parser.add_option(flag_list_directories_only, "List directories themselves, not their contents", "directory", 'd');
  99. args_parser.add_option(flag_long, "Display long info", "long", 'l');
  100. args_parser.add_option(flag_sort_by_timestamp, "Sort files by timestamp", nullptr, 't');
  101. args_parser.add_option(flag_reverse_sort, "Reverse sort order", "reverse", 'r');
  102. args_parser.add_option(flag_classify, "Append a file type indicator to entries", "classify", 'F');
  103. args_parser.add_option(flag_colorize, "Use pretty colors", nullptr, 'G');
  104. args_parser.add_option(flag_show_inode, "Show inode ids", "inode", 'i');
  105. args_parser.add_option(flag_print_numeric, "In long format, display numeric UID/GID", "numeric-uid-gid", 'n');
  106. args_parser.add_option(flag_hide_group, "In long format, do not show group information", nullptr, 'o');
  107. args_parser.add_option(flag_human_readable, "Print human-readable sizes", "human-readable", 'h');
  108. args_parser.add_option(flag_disable_hyperlinks, "Disable hyperlinks", "no-hyperlinks", 'K');
  109. args_parser.add_positional_argument(paths, "Directory to list", "path", Core::ArgsParser::Required::No);
  110. args_parser.parse(argc, argv);
  111. if (flag_show_almost_all_dotfiles)
  112. flag_show_dotfiles = true;
  113. if (flag_long) {
  114. setpwent();
  115. for (auto* pwd = getpwent(); pwd; pwd = getpwent())
  116. users.set(pwd->pw_uid, pwd->pw_name);
  117. endpwent();
  118. setgrent();
  119. for (auto* grp = getgrent(); grp; grp = getgrent())
  120. groups.set(grp->gr_gid, grp->gr_name);
  121. endgrent();
  122. }
  123. auto do_file_system_object = [&](const char* path) {
  124. if (flag_long)
  125. return do_file_system_object_long(path);
  126. return do_file_system_object_short(path);
  127. };
  128. int status = 0;
  129. if (paths.is_empty()) {
  130. status = do_file_system_object(".");
  131. } else if (paths.size() == 1) {
  132. status = do_file_system_object(paths[0]);
  133. } else {
  134. Vector<const char*> exists;
  135. for (auto& path : paths) {
  136. if (Core::File::exists(path)) {
  137. exists.append(path);
  138. } else {
  139. status = do_file_system_object(path);
  140. }
  141. }
  142. for (size_t i = 0; i < exists.size(); ++i) {
  143. auto path = exists.at(i);
  144. printf("%s:\n", path);
  145. status = do_file_system_object(path);
  146. if (i + 1 == exists.size() - 1) {
  147. printf("\n");
  148. }
  149. }
  150. }
  151. return status;
  152. }
  153. static int print_escaped(const char* name)
  154. {
  155. int printed = 0;
  156. Utf8View utf8_name(name);
  157. if (utf8_name.validate()) {
  158. printf("%s", name);
  159. return utf8_name.length();
  160. }
  161. for (int i = 0; name[i] != '\0'; i++) {
  162. if (isprint(name[i])) {
  163. putchar(name[i]);
  164. printed++;
  165. } else {
  166. printed += printf("\\%03d", name[i]);
  167. }
  168. }
  169. return printed;
  170. }
  171. static String& hostname()
  172. {
  173. static String s_hostname;
  174. if (s_hostname.is_null()) {
  175. char buffer[HOST_NAME_MAX];
  176. if (gethostname(buffer, sizeof(buffer)) == 0)
  177. s_hostname = buffer;
  178. else
  179. s_hostname = "localhost";
  180. }
  181. return s_hostname;
  182. }
  183. static size_t print_name(const struct stat& st, const String& name, const char* path_for_link_resolution, const char* path_for_hyperlink)
  184. {
  185. if (!flag_disable_hyperlinks) {
  186. auto full_path = Core::File::real_path_for(path_for_hyperlink);
  187. if (!full_path.is_null()) {
  188. out("\033]8;;file://{}{}\033\\", hostname(), full_path);
  189. }
  190. }
  191. size_t nprinted = 0;
  192. if (!flag_colorize || !output_is_terminal) {
  193. nprinted = printf("%s", name.characters());
  194. } else {
  195. const char* begin_color = "";
  196. const char* end_color = "\033[0m";
  197. if (st.st_mode & S_ISVTX)
  198. begin_color = "\033[42;30;1m";
  199. else if (st.st_mode & S_ISUID)
  200. begin_color = "\033[41;1m";
  201. else if (st.st_mode & S_ISGID)
  202. begin_color = "\033[43;1m";
  203. else if (S_ISLNK(st.st_mode))
  204. begin_color = "\033[36;1m";
  205. else if (S_ISDIR(st.st_mode))
  206. begin_color = "\033[34;1m";
  207. else if (st.st_mode & 0111)
  208. begin_color = "\033[32;1m";
  209. else if (S_ISSOCK(st.st_mode))
  210. begin_color = "\033[35;1m";
  211. else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))
  212. begin_color = "\033[33;1m";
  213. printf("%s", begin_color);
  214. nprinted = print_escaped(name.characters());
  215. printf("%s", end_color);
  216. }
  217. if (S_ISLNK(st.st_mode)) {
  218. if (path_for_link_resolution) {
  219. auto link_destination = Core::File::read_link(path_for_link_resolution);
  220. if (link_destination.is_null()) {
  221. perror("readlink");
  222. } else {
  223. nprinted += printf(" -> ") + print_escaped(link_destination.characters());
  224. }
  225. } else {
  226. if (flag_classify)
  227. nprinted += printf("@");
  228. }
  229. } else if (S_ISDIR(st.st_mode)) {
  230. if (flag_classify)
  231. nprinted += printf("/");
  232. } else if (st.st_mode & 0111) {
  233. if (flag_classify)
  234. nprinted += printf("*");
  235. }
  236. if (!flag_disable_hyperlinks) {
  237. printf("\033]8;;\033\\");
  238. }
  239. return nprinted;
  240. }
  241. static bool print_filesystem_object(const String& path, const String& name, const struct stat& st)
  242. {
  243. if (flag_show_inode)
  244. printf("%08u ", st.st_ino);
  245. if (S_ISDIR(st.st_mode))
  246. printf("d");
  247. else if (S_ISLNK(st.st_mode))
  248. printf("l");
  249. else if (S_ISBLK(st.st_mode))
  250. printf("b");
  251. else if (S_ISCHR(st.st_mode))
  252. printf("c");
  253. else if (S_ISFIFO(st.st_mode))
  254. printf("f");
  255. else if (S_ISSOCK(st.st_mode))
  256. printf("s");
  257. else if (S_ISREG(st.st_mode))
  258. printf("-");
  259. else
  260. printf("?");
  261. printf("%c%c%c%c%c%c%c%c",
  262. st.st_mode & S_IRUSR ? 'r' : '-',
  263. st.st_mode & S_IWUSR ? 'w' : '-',
  264. st.st_mode & S_ISUID ? 's' : (st.st_mode & S_IXUSR ? 'x' : '-'),
  265. st.st_mode & S_IRGRP ? 'r' : '-',
  266. st.st_mode & S_IWGRP ? 'w' : '-',
  267. st.st_mode & S_ISGID ? 's' : (st.st_mode & S_IXGRP ? 'x' : '-'),
  268. st.st_mode & S_IROTH ? 'r' : '-',
  269. st.st_mode & S_IWOTH ? 'w' : '-');
  270. if (st.st_mode & S_ISVTX)
  271. printf("t");
  272. else
  273. printf("%c", st.st_mode & S_IXOTH ? 'x' : '-');
  274. printf(" %3u", st.st_nlink);
  275. auto username = users.get(st.st_uid);
  276. if (!flag_print_numeric && username.has_value()) {
  277. printf(" %7s", username.value().characters());
  278. } else {
  279. printf(" %7u", st.st_uid);
  280. }
  281. if (!flag_hide_group) {
  282. auto groupname = groups.get(st.st_gid);
  283. if (!flag_print_numeric && groupname.has_value()) {
  284. printf(" %7s", groupname.value().characters());
  285. } else {
  286. printf(" %7u", st.st_gid);
  287. }
  288. }
  289. if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
  290. printf(" %4u,%4u ", major(st.st_rdev), minor(st.st_rdev));
  291. } else {
  292. if (flag_human_readable) {
  293. printf(" %10s ", human_readable_size(st.st_size).characters());
  294. } else {
  295. printf(" %10lld ", st.st_size);
  296. }
  297. }
  298. printf(" %s ", Core::DateTime::from_timestamp(st.st_mtime).to_string().characters());
  299. print_name(st, name, path.characters(), path.characters());
  300. printf("\n");
  301. return true;
  302. }
  303. static int do_file_system_object_long(const char* path)
  304. {
  305. if (flag_list_directories_only) {
  306. struct stat stat;
  307. int rc = lstat(path, &stat);
  308. if (rc < 0) {
  309. perror("lstat");
  310. memset(&stat, 0, sizeof(stat));
  311. }
  312. if (print_filesystem_object(path, path, stat))
  313. return 0;
  314. return 2;
  315. }
  316. auto flags = Core::DirIterator::SkipDots;
  317. if (flag_show_dotfiles)
  318. flags = Core::DirIterator::Flags::NoFlags;
  319. if (flag_show_almost_all_dotfiles)
  320. flags = Core::DirIterator::SkipParentAndBaseDir;
  321. Core::DirIterator di(path, flags);
  322. if (di.has_error()) {
  323. if (di.error() == ENOTDIR) {
  324. struct stat stat;
  325. int rc = lstat(path, &stat);
  326. if (rc < 0) {
  327. perror("lstat");
  328. memset(&stat, 0, sizeof(stat));
  329. }
  330. if (print_filesystem_object(path, path, stat))
  331. return 0;
  332. return 2;
  333. }
  334. fprintf(stderr, "%s: %s\n", path, di.error_string());
  335. return 1;
  336. }
  337. struct FileMetadata {
  338. String name;
  339. String path;
  340. struct stat stat;
  341. };
  342. Vector<FileMetadata> files;
  343. while (di.has_next()) {
  344. FileMetadata metadata;
  345. metadata.name = di.next_path();
  346. VERIFY(!metadata.name.is_empty());
  347. if (metadata.name.ends_with('~') && flag_ignore_backups && metadata.name != path)
  348. continue;
  349. StringBuilder builder;
  350. builder.append(path);
  351. builder.append('/');
  352. builder.append(metadata.name);
  353. metadata.path = builder.to_string();
  354. VERIFY(!metadata.path.is_null());
  355. int rc = lstat(metadata.path.characters(), &metadata.stat);
  356. if (rc < 0) {
  357. perror("lstat");
  358. memset(&metadata.stat, 0, sizeof(metadata.stat));
  359. }
  360. files.append(move(metadata));
  361. }
  362. quick_sort(files, [](auto& a, auto& b) {
  363. if (flag_sort_by_timestamp) {
  364. if (flag_reverse_sort)
  365. return a.stat.st_mtime > b.stat.st_mtime;
  366. return a.stat.st_mtime < b.stat.st_mtime;
  367. }
  368. // Fine, sort by name then!
  369. if (flag_reverse_sort)
  370. return a.name > b.name;
  371. return a.name < b.name;
  372. });
  373. for (auto& file : files) {
  374. if (!print_filesystem_object(file.path, file.name, file.stat))
  375. return 2;
  376. }
  377. return 0;
  378. }
  379. static bool print_filesystem_object_short(const char* path, const char* name, size_t* nprinted)
  380. {
  381. struct stat st;
  382. int rc = lstat(path, &st);
  383. if (rc == -1) {
  384. printf("lstat(%s) failed: %s\n", path, strerror(errno));
  385. return false;
  386. }
  387. if (flag_show_inode)
  388. printf("%08u ", st.st_ino);
  389. *nprinted = print_name(st, name, nullptr, path);
  390. return true;
  391. }
  392. int do_file_system_object_short(const char* path)
  393. {
  394. if (flag_list_directories_only) {
  395. size_t nprinted = 0;
  396. bool status = print_filesystem_object_short(path, path, &nprinted);
  397. printf("\n");
  398. if (status)
  399. return 0;
  400. return 2;
  401. }
  402. auto flags = Core::DirIterator::SkipDots;
  403. if (flag_show_dotfiles)
  404. flags = Core::DirIterator::Flags::NoFlags;
  405. if (flag_show_almost_all_dotfiles)
  406. flags = Core::DirIterator::SkipParentAndBaseDir;
  407. Core::DirIterator di(path, flags);
  408. if (di.has_error()) {
  409. if (di.error() == ENOTDIR) {
  410. size_t nprinted = 0;
  411. bool status = print_filesystem_object_short(path, path, &nprinted);
  412. printf("\n");
  413. if (status)
  414. return 0;
  415. return 2;
  416. }
  417. fprintf(stderr, "%s: %s\n", path, di.error_string());
  418. return 1;
  419. }
  420. Vector<String> names;
  421. size_t longest_name = 0;
  422. while (di.has_next()) {
  423. String name = di.next_path();
  424. if (name.ends_with('~') && flag_ignore_backups && name != path)
  425. continue;
  426. names.append(name);
  427. if (names.last().length() > longest_name)
  428. longest_name = name.length();
  429. }
  430. quick_sort(names);
  431. size_t printed_on_row = 0;
  432. size_t nprinted = 0;
  433. for (size_t i = 0; i < names.size(); ++i) {
  434. auto& name = names[i];
  435. StringBuilder builder;
  436. builder.append(path);
  437. builder.append('/');
  438. builder.append(name);
  439. if (!print_filesystem_object_short(builder.to_string().characters(), name.characters(), &nprinted))
  440. return 2;
  441. int offset = 0;
  442. if (terminal_columns > longest_name)
  443. offset = terminal_columns % longest_name / (terminal_columns / longest_name);
  444. // The offset must be at least 2 because:
  445. // - With each file an additional char is printed e.g. '@','*'.
  446. // - Each filename must be separated by a space.
  447. size_t column_width = longest_name + max(offset, 2);
  448. printed_on_row += column_width;
  449. for (size_t j = nprinted; i != (names.size() - 1) && j < column_width; ++j)
  450. printf(" ");
  451. if ((printed_on_row + column_width) >= terminal_columns) {
  452. printf("\n");
  453. printed_on_row = 0;
  454. }
  455. }
  456. if (printed_on_row)
  457. printf("\n");
  458. return 0;
  459. }