logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

df.c (11657B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 202405L
  5. #define _DEFAULT_SOURCE // mntent in glibc 2.19+
  6. #include "../config.h"
  7. #include "../lib/reallocarray.h"
  8. #include "../libutils/getopt_nolong.h"
  9. #include "../libutils/humanize.h"
  10. #include <ctype.h> // iscntrl, isspace
  11. #include <errno.h> // errno
  12. #include <mntent.h>
  13. #include <stdbool.h>
  14. #include <stdio.h> // printf
  15. #include <stdlib.h> // abort, exit
  16. #include <string.h> // strerror
  17. #include <sys/stat.h> // stat, dev_t
  18. #include <sys/statvfs.h>
  19. #include <unistd.h> // getopt
  20. #ifdef HAS_GETOPT_LONG
  21. #include <getopt.h>
  22. #endif
  23. #define STR(s) #s
  24. /*
  25. * Rough idea of builtin filesystems in Linux 6.12.31:
  26. * $ grep -RI '\bregister_filesystem(' /usr/src/linux/fs/ | wc -l
  27. * 79
  28. */
  29. #define DF_MNT_TYPE_MAX 128
  30. // Grabbed from OpenRC rc-functions.sh
  31. // clang-format off
  32. static const char *net_fs_list[] = {
  33. "afs", "ceph", "cifs", "coda", "davfs", "fuse", "fuse.glusterfs",
  34. "fuse.sshfs", "gfs", "glusterfs", "lustre", "ncpfs", "nfs", "nfs4",
  35. "ocfs2", "shfs", "smbfs"
  36. };
  37. // clang-format on
  38. blksize_t forced_bsize = 0;
  39. const char *argv0 = "df";
  40. // Replaces control characters and whitespaces with '?' in-place (no allocation)
  41. static void
  42. static_escape(char *str)
  43. {
  44. for(size_t i = 0; i < strlen(str); i++)
  45. if(iscntrl(str[i]) || isspace(str[i])) str[i] = '?';
  46. }
  47. int
  48. main(int argc, char *argv[])
  49. {
  50. bool opt_P = false, opt_h = false, opt_a = false, opt_T = false, opt_l = false, opt_i = false;
  51. int fs_col_width = 20;
  52. dev_t *devices = NULL;
  53. size_t excluded_count = 0;
  54. static char *excluded[DF_MNT_TYPE_MAX];
  55. size_t only_count = 0;
  56. static char *only[DF_MNT_TYPE_MAX];
  57. #ifdef HAS_GETOPT_LONG
  58. // Strictly for GNUisms compatibility so no long-only options
  59. // clang-format off
  60. static struct option opts[] = {
  61. {"all", no_argument, NULL, 'a'},
  62. {"human-readable", no_argument, NULL, 'h'},
  63. {"inodes", no_argument, NULL, 'i'},
  64. {"local", no_argument, NULL, 'l'},
  65. {"portability", no_argument, NULL, 'P'},
  66. {"type", required_argument, NULL, 't'},
  67. {"exclude-type", required_argument, NULL, 'x'},
  68. {0, 0, 0, 0},
  69. };
  70. // clang-format on
  71. // Need + as first character to get POSIX-style option parsing
  72. for(int c = -1; (c = getopt_long(argc, argv, "+:ahilPkTt:x:", opts, NULL)) != -1;)
  73. #else
  74. for(int c = -1; (c = getopt_nolong(argc, argv, ":ahilPkTt:x:")) != -1;)
  75. #endif
  76. {
  77. switch(c)
  78. {
  79. case 'a':
  80. opt_a = true;
  81. break;
  82. case 'P':
  83. if(forced_bsize == 0) forced_bsize = 512;
  84. opt_P = true;
  85. break;
  86. case 'k':
  87. forced_bsize = 1024;
  88. break;
  89. case 'h':
  90. opt_h = true;
  91. fs_col_width = 30;
  92. break;
  93. case 'i':
  94. opt_i = true;
  95. break;
  96. case 'l':
  97. opt_l = true;
  98. break;
  99. case 'T':
  100. opt_T = true;
  101. break;
  102. case 't':
  103. if(only_count >= (DF_MNT_TYPE_MAX - 1))
  104. {
  105. fprintf(
  106. stderr,
  107. "%s: error: Can only select up to " STR(DF_MNT_TYPE_MAX) " mnt_types via option `-t`\n",
  108. argv0);
  109. return 1;
  110. }
  111. only[only_count++] = optarg;
  112. break;
  113. case 'x':
  114. if(excluded_count >= (DF_MNT_TYPE_MAX - 1))
  115. {
  116. fprintf(
  117. stderr,
  118. "%s: error: Can only select up to " STR(DF_MNT_TYPE_MAX) " mnt_types via option `-x`\n",
  119. argv0);
  120. return 1;
  121. }
  122. excluded[excluded_count++] = optarg;
  123. break;
  124. case ':':
  125. fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
  126. return 1;
  127. case '?':
  128. GETOPT_UNKNOWN_OPT
  129. return 1;
  130. }
  131. }
  132. if(opt_P && opt_T)
  133. {
  134. fprintf(stderr, "%s: error: Options -P and -T are incompatible\n", argv0);
  135. return 1;
  136. }
  137. if(opt_P) opt_h = false;
  138. argc -= optind;
  139. argv += optind;
  140. int args_left = argc != 0 ? argc : 1;
  141. bool tty_out = isatty(1);
  142. int col_width = tty_out ? 10 : 0;
  143. if(!tty_out)
  144. {
  145. errno = 0;
  146. fs_col_width = 0;
  147. }
  148. dev_t *arg_devs = NULL;
  149. if(argc > 0)
  150. {
  151. arg_devs = calloc(argc, sizeof(dev_t));
  152. if(arg_devs == NULL)
  153. {
  154. fprintf(stderr, "%s: error: Failed to allocate arg_devs array: %s\n", argv0, strerror(errno));
  155. return 1;
  156. }
  157. }
  158. for(int i = 0; i < argc; i++)
  159. {
  160. struct stat file_stats;
  161. if(stat(argv[i], &file_stats) != 0)
  162. {
  163. fprintf(stderr,
  164. "%s: error: Failed getting status for file '%s': %s\n",
  165. argv0,
  166. argv[i],
  167. strerror(errno));
  168. goto error;
  169. }
  170. arg_devs[i] = file_stats.st_dev;
  171. }
  172. // Begin: Print header
  173. printf("%-*s ", fs_col_width, "Filesystem");
  174. if(opt_T) printf("%*s ", col_width, "Type");
  175. if(opt_i)
  176. {
  177. printf("%*s %*s %*s ", col_width, "Inodes", col_width, "Iused", col_width, "IFree");
  178. if(opt_P)
  179. printf("IUse%% Mounted on\n");
  180. else
  181. printf("IUse%% Mountpoint\n");
  182. }
  183. else
  184. {
  185. if(forced_bsize != 0)
  186. printf("%zd-blocks ", forced_bsize);
  187. else
  188. printf("%*s ", col_width, "Total");
  189. printf("%*s %*s ", col_width, "Used", col_width, "Available");
  190. if(opt_P)
  191. printf("Capacity Mounted on\n");
  192. else
  193. printf("Use%% Mountpoint\n");
  194. }
  195. // End: Print header
  196. FILE *mounted = setmntent(MOUNTED, "r");
  197. if(mounted == NULL)
  198. {
  199. fprintf(stderr,
  200. "%s: error: Failed opening setmntent(\"" MOUNTED "\", \"r\"): %s\n",
  201. argv0,
  202. strerror(errno));
  203. goto error;
  204. }
  205. // Linux has a configurable limit of maximum mounts which defaults to 100_000
  206. // See /proc/sys/fs/mount-max introduced in Linux 4.9 for CVE-2016-6213
  207. // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d29216842a85c7970c536108e093963f02714498
  208. //
  209. // Which is way too much to be either stack-allocated or statically allocated:
  210. // 100000*sizeof(dev_t) = 100000*8 bytes ≈ 781.25 KiB
  211. // So reallocarray to the rescue
  212. size_t devices_found = 0;
  213. size_t devices_len = 100;
  214. devices = reallocarray(NULL, devices_len, sizeof(dev_t));
  215. if(!devices)
  216. {
  217. fprintf(stderr,
  218. "%s: error: Failed to allocate memory for storing (%zd) devices: %s\n",
  219. argv0,
  220. devices_len,
  221. strerror(errno));
  222. goto error;
  223. }
  224. // Even with argc>0 we still need to go over mntent for the filesystem mountpoint and type
  225. while(args_left > 0)
  226. {
  227. struct mntent *mntent = getmntent(mounted);
  228. if(mntent == NULL) break;
  229. if(excluded_count > 0)
  230. {
  231. bool exclude = false;
  232. for(size_t i = 0; i < excluded_count; i++)
  233. if(strcmp(excluded[i], mntent->mnt_type) == 0)
  234. {
  235. exclude = true;
  236. break;
  237. }
  238. if(exclude) continue;
  239. }
  240. if(only_count > 0)
  241. {
  242. bool include = false;
  243. for(size_t i = 0; i < only_count; i++)
  244. if(strcmp(only[i], mntent->mnt_type) == 0)
  245. {
  246. include = true;
  247. break;
  248. }
  249. if(!include) continue;
  250. }
  251. if(opt_l)
  252. {
  253. bool remote = false;
  254. for(size_t i = 0; i < sizeof(net_fs_list) / sizeof(char *); i++)
  255. if(strcmp(net_fs_list[i], mntent->mnt_type) == 0)
  256. {
  257. remote = true;
  258. break;
  259. }
  260. if(remote) continue;
  261. }
  262. struct stat file_stats;
  263. if(!opt_a || argc > 0)
  264. {
  265. if(stat(mntent->mnt_dir, &file_stats) != 0)
  266. {
  267. fprintf(stderr,
  268. "%s: warning: Failed getting status for file '%s': %s\n",
  269. argv0,
  270. mntent->mnt_dir,
  271. strerror(errno));
  272. errno = 0;
  273. }
  274. }
  275. if(argc > 0)
  276. {
  277. bool found = false;
  278. for(int i = 0; i < argc; i++)
  279. if(arg_devs[i] == file_stats.st_dev)
  280. {
  281. found = true;
  282. break;
  283. }
  284. if(!found) continue;
  285. args_left--;
  286. }
  287. if(!opt_a)
  288. {
  289. bool dupe = false;
  290. for(size_t i = 0; i < devices_found; i++)
  291. if(devices[i] == file_stats.st_dev)
  292. {
  293. dupe = true;
  294. break;
  295. }
  296. if(dupe) continue;
  297. if(devices_found + 1 >= devices_len)
  298. {
  299. devices_len *= 2;
  300. if(devices_len <= 0) abort();
  301. devices = reallocarray(devices, devices_len, sizeof(dev_t));
  302. if(!devices)
  303. {
  304. fprintf(stderr,
  305. "%s: error: Failed to allocate memory for storing (%zd) devices: %s\n",
  306. argv0,
  307. devices_len,
  308. strerror(errno));
  309. goto error;
  310. }
  311. }
  312. devices[devices_found++] = file_stats.st_dev;
  313. }
  314. // Note: musl prior to 1.2.5 has broken getmntent when octal sequences and carriage return is used
  315. // https://git.musl-libc.org/cgit/musl/commit/src/misc/mntent.c?id=f314e133929b6379eccc632bef32eaebb66a7335
  316. // https://git.musl-libc.org/cgit/musl/commit/src/misc/mntent.c?id=ee1d39bc1573c1ae49ee6b658938b56bbef95a6c
  317. struct statvfs stats;
  318. if(statvfs(mntent->mnt_dir, &stats) != 0)
  319. {
  320. fprintf(stderr,
  321. "%s: warning: Failed getting statistics for filesystem '%s': %s\n",
  322. argv0,
  323. mntent->mnt_dir,
  324. strerror(errno));
  325. errno = 0;
  326. static_escape(mntent->mnt_fsname);
  327. static_escape(mntent->mnt_dir);
  328. if(opt_a)
  329. {
  330. printf("%-*s ", fs_col_width, mntent->mnt_fsname);
  331. if(opt_T) printf("%*s ", col_width, mntent->mnt_type);
  332. printf("%*s ", col_width, "-"); // total
  333. printf("%*s ", col_width, "-"); // used
  334. printf("%*s ", col_width, "-"); // free
  335. printf("%*s ", tty_out ? 3 : 0, "-"); // percent
  336. printf("%s\n", mntent->mnt_dir);
  337. }
  338. continue;
  339. }
  340. // Skip null filesystems
  341. if(!opt_a && stats.f_blocks == 0) continue;
  342. // Needs to be done after calling statvfs(3) and stat(3)
  343. static_escape(mntent->mnt_fsname);
  344. static_escape(mntent->mnt_dir);
  345. printf("%-*s ", fs_col_width, mntent->mnt_fsname);
  346. if(opt_T) printf("%*s ", col_width, mntent->mnt_type);
  347. if(opt_i)
  348. {
  349. fsfilcnt_t used = stats.f_files - stats.f_ffree;
  350. fsfilcnt_t percent = (used / stats.f_files) * 100;
  351. if(opt_h && !opt_P)
  352. {
  353. struct si_scale total_scl = dtosi(stats.f_files, false);
  354. struct si_scale used_scl = dtosi(used, false);
  355. struct si_scale free_scl = dtosi(stats.f_ffree, false);
  356. int width_num = tty_out ? col_width - 1 : 0;
  357. int width_pre = tty_out ? 1 : 0;
  358. printf("%*.2f%-*s ", width_num, total_scl.number, width_pre, total_scl.prefix);
  359. printf("%*.2f%-*s ", width_num, used_scl.number, width_pre, used_scl.prefix);
  360. printf("%*.2f%-*s ", width_num, free_scl.number, width_pre, free_scl.prefix);
  361. }
  362. else
  363. {
  364. printf("%*zd ", col_width, stats.f_files);
  365. printf("%*zd ", col_width, used);
  366. printf("%*zd ", col_width, stats.f_ffree);
  367. }
  368. printf("%*zd%% ", tty_out ? 4 : 0, percent);
  369. printf("%s\n", mntent->mnt_dir);
  370. continue;
  371. }
  372. off_t percent = 0;
  373. off_t total = stats.f_frsize * (stats.f_blocks != 0 ? stats.f_blocks : 1);
  374. off_t free = stats.f_bfree * (stats.f_bsize != 0 ? stats.f_bsize : 1);
  375. off_t used = total - free;
  376. if(used + free)
  377. {
  378. percent = (used * 100) / (used + free);
  379. if(used * 100 != percent * (used + free)) percent++;
  380. }
  381. if(forced_bsize != 0)
  382. {
  383. total /= forced_bsize;
  384. free /= forced_bsize;
  385. used /= forced_bsize;
  386. }
  387. if(opt_h && !opt_P)
  388. {
  389. struct si_scale total_scl = dtosi(total, true);
  390. struct si_scale used_scl = dtosi(used, true);
  391. struct si_scale free_scl = dtosi(free, true);
  392. int width_num = tty_out ? col_width - 3 : 0;
  393. int width_pre = tty_out ? 3 : 0;
  394. printf("%*.2f%-*s ", width_num, total_scl.number, width_pre, total_scl.prefix);
  395. printf("%*.2f%-*s ", width_num, used_scl.number, width_pre, used_scl.prefix);
  396. printf("%*.2f%-*s ", width_num, free_scl.number, width_pre, free_scl.prefix);
  397. }
  398. else
  399. {
  400. printf("%*zd ", col_width, total);
  401. printf("%*zd ", col_width, used);
  402. printf("%*zd ", col_width, free);
  403. }
  404. printf("%*zd%% ", tty_out ? 3 : 0, percent);
  405. printf("%s\n", mntent->mnt_dir);
  406. }
  407. endmntent(mounted);
  408. free(devices);
  409. free(arg_devs);
  410. return 0;
  411. error:
  412. free(devices);
  413. free(arg_devs);
  414. return 1;
  415. }