• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* lsattr.c - List file attributes on a Linux second extended file system.
2  *
3  * Copyright 2013 Ranjan Kumar <ranjankumar.bth@gmail.com>
4  * Copyright 2013 Kyungwan Han <asura321@gmail.com>
5  *
6  * No Standard.
7  *
8  * TODO cleanup
9 
10 USE_LSATTR(NEWTOY(lsattr, "ldapvR", TOYFLAG_BIN))
11 USE_CHATTR(NEWTOY(chattr, "?p#v#R", TOYFLAG_BIN))
12 
13 config LSATTR
14   bool "lsattr"
15   default y
16   help
17     usage: lsattr [-Radlpv] [FILE...]
18 
19     List file attributes on a Linux file system.
20     Flag letters are defined in chattr help.
21 
22     -R	Recursively list attributes of directories and their contents
23     -a	List all files in directories, including files that start with '.'
24     -d	List directories like other files, rather than listing their contents
25     -l	List long flag names
26     -p	List the file's project number
27     -v	List the file's version/generation number
28 
29 config CHATTR
30   bool "chattr"
31   default y
32   help
33     usage: chattr [-R] [-+=AacDdijsStTu] [-p PROJID] [-v VERSION] [FILE...]
34 
35     Change file attributes on a Linux file system.
36 
37     -R	Recurse
38     -p	Set the file's project number
39     -v	Set the file's version/generation number
40 
41     Operators:
42       '-' Remove attributes
43       '+' Add attributes
44       '=' Set attributes
45 
46     Attributes:
47       A  No atime                     a  Append only
48       C  No COW                       c  Compression
49       D  Synchronous dir updates      d  No dump
50       E  Encrypted                    e  Extents
51       F  Case-insensitive (casefold)
52       I  Indexed directory            i  Immutable
53       j  Journal data
54       N  Inline data in inode
55       P  Project hierarchy
56       S  Synchronous file updates     s  Secure delete
57       T  Top of dir hierarchy         t  No tail-merging
58       u  Allow undelete
59       V  Verity
60 */
61 #define FOR_lsattr
62 #include "toys.h"
63 #include <linux/fs.h>
64 
65 GLOBALS(
66   long v, p;
67 
68   unsigned add, rm, set;
69   // !add and !rm tell us whether they were used, but `chattr =` is meaningful.
70   int have_set;
71 )
72 
73 // Added more recently than the 7 year support horizon. TODO: remove
74 #ifndef FS_INLINE_DATA_FL
75 #define FS_INLINE_DATA_FL 0x10000000 // commit 68ce7bfcd995a 2016-01-08
76 #endif
77 #ifndef FS_PROJINHERIT_FL
78 #define FS_PROJINHERIT_FL 0x20000000 // commit 8b4953e13f4c5 2015-10-17
79 #endif
80 #ifndef FS_CASEFOLD_FL
81 #define FS_CASEFOLD_FL    0x40000000 // commit 71e90b4654a92 2019-07-23
82 #endif
83 #ifndef FS_VERITY_FL
84 #define FS_VERITY_FL      0x00100000 // commit fe9918d3b228b 2019-07-22
85 #endif
86 
87 #ifndef FS_IOC_FSGETXATTR
88 // commit 334e580a6f97e 2016-01-04
89 struct fsxattr {
90   unsigned fsx_xflags, fsx_extsize, fsx_nextents, fsx_projid, fsx_cowextsize;
91   char fsx_pad[8];
92 };
93 #define FS_IOC_FSGETXATTR _IOR('X', 31, struct fsxattr)
94 #define FS_IOC_FSSETXATTR _IOW('X', 32, struct fsxattr)
95 #endif
96 
97 static struct ext2_attr {
98   char *name;
99   unsigned flag;
100   char opt;
101 } e2attrs[] = {
102   // Do not sort! These are in the order that lsattr outputs them.
103   {"Secure_Deletion",               FS_SECRM_FL,        's'},
104   {"Undelete",                      FS_UNRM_FL,         'u'},
105   {"Synchronous_Updates",           FS_SYNC_FL,         'S'},
106   {"Synchronous_Directory_Updates", FS_DIRSYNC_FL,      'D'},
107   {"Immutable",                     FS_IMMUTABLE_FL,    'i'},
108   {"Append_Only",                   FS_APPEND_FL,       'a'},
109   {"No_Dump",                       FS_NODUMP_FL,       'd'},
110   {"No_Atime",                      FS_NOATIME_FL,      'A'},
111   {"Compression_Requested",         FS_COMPR_FL,        'c'},
112   // FS_ENCRYPT_FL added to linux 4.5 march 2016, +y7 = 2023
113   {"Encrypted",                     0x800,              'E'},
114   {"Journaled_Data",                FS_JOURNAL_DATA_FL, 'j'},
115   {"Indexed_directory",             FS_INDEX_FL,        'I'},
116   {"No_Tailmerging",                FS_NOTAIL_FL,       't'},
117   {"Top_of_Directory_Hierarchies",  FS_TOPDIR_FL,       'T'},
118   {"Extents",                       FS_EXTENT_FL,       'e'},
119   {"No_COW",                        FS_NOCOW_FL,        'C'},
120   {"Casefold",                      FS_CASEFOLD_FL,     'F'},
121   {"Inline_Data",                   FS_INLINE_DATA_FL,  'N'},
122   {"Project_Hierarchy",             FS_PROJINHERIT_FL,  'P'},
123   {"Verity",                        FS_VERITY_FL,       'V'},
124   {NULL,                            0,                  0},
125 };
126 
127 // Get file flags on a Linux second extended file system.
ext2_getflag(int fd,struct stat * sb,unsigned * flag)128 static int ext2_getflag(int fd, struct stat *sb, unsigned *flag)
129 {
130   if(!S_ISREG(sb->st_mode) && !S_ISDIR(sb->st_mode)) {
131     errno = EOPNOTSUPP;
132     return -1;
133   }
134   return (ioctl(fd, FS_IOC_GETFLAGS, (void*)flag));
135 }
136 
attrstr(unsigned attrs,int full)137 static char *attrstr(unsigned attrs, int full)
138 {
139   struct ext2_attr *a = e2attrs;
140   char *s = toybuf;
141 
142   for (; a->name; a++)
143     if (attrs & a->flag) *s++ = a->opt;
144     else if (full) *s++ = '-';
145   *s = 0;
146 
147   return toybuf;
148 }
149 
print_file_attr(char * path)150 static void print_file_attr(char *path)
151 {
152   unsigned flag = 0, version = 0;
153   int fd = -1;
154   struct stat sb;
155 
156   if (!stat(path, &sb) && !S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode)) {
157     errno = EOPNOTSUPP;
158     goto error;
159   }
160   if (-1 == (fd=open(path, O_RDONLY | O_NONBLOCK))) goto error;
161 
162   if (FLAG(p)) {
163     struct fsxattr fsx;
164 
165     if (ioctl(fd, FS_IOC_FSGETXATTR, &fsx)) goto error;
166     xprintf("%5u ", fsx.fsx_projid);
167   }
168   if (FLAG(v)) {
169     if (ioctl(fd, FS_IOC_GETVERSION, (void*)&version) < 0) goto error;
170     xprintf("%-10u ", version);
171   }
172 
173   if (ext2_getflag(fd, &sb, &flag) < 0) perror_msg("reading flags '%s'", path);
174   else {
175     struct ext2_attr *ptr = e2attrs;
176 
177     if (FLAG(l)) {
178       int name_found = 0;
179 
180       xprintf("%-50s ", path);
181       for (; ptr->name; ptr++) {
182         if (flag & ptr->flag) {
183           if (name_found) xprintf(", "); //for formatting.
184           xprintf("%s", ptr->name);
185           name_found = 1;
186         }
187       }
188       if (!name_found) xprintf("---");
189       xputc('\n');
190     } else xprintf("%s %s\n", attrstr(flag, 1), path);
191   }
192   path = 0;
193 error:
194   xclose(fd);
195   if (path) perror_msg("reading '%s'", path);
196 }
197 
198 // Get directory information.
retell_dir(struct dirtree * root)199 static int retell_dir(struct dirtree *root)
200 {
201   char *fpath = 0;
202 
203   if (root->again) {
204     xputc('\n');
205 
206     return 0;
207   }
208   if (S_ISDIR(root->st.st_mode) && !root->parent)
209     return (DIRTREE_RECURSE | DIRTREE_COMEAGAIN);
210 
211   fpath = dirtree_path(root, NULL);
212   //Special case: with '-a' option and '.'/'..' also included in printing list.
213   if (*root->name != '.' || FLAG(a)) {
214     print_file_attr(fpath);
215     if (S_ISDIR(root->st.st_mode) && FLAG(R) && dirtree_notdotdot(root)) {
216       xprintf("\n%s:\n", fpath);
217       free(fpath);
218       return (DIRTREE_RECURSE | DIRTREE_COMEAGAIN);
219     }
220   }
221   free(fpath);
222 
223   return 0;
224 }
225 
lsattr_main(void)226 void lsattr_main(void)
227 {
228   if (!*toys.optargs) dirtree_read(".", retell_dir);
229   else
230     for (; *toys.optargs; toys.optargs++) {
231       struct stat sb;
232 
233       if (lstat(*toys.optargs, &sb)) perror_msg("stat '%s'", *toys.optargs);
234       else if (S_ISDIR(sb.st_mode) && !FLAG(d))
235         dirtree_read(*toys.optargs, retell_dir);
236       else print_file_attr(*toys.optargs);// to handle "./Filename" or "./Dir"
237     }
238 }
239 
240 // Switch gears from lsattr to chattr.
241 #define FOR_chattr
242 #include "generated/flags.h"
243 
244 // Set file flags on a Linux second extended file system.
ext2_setflag(int fd,struct stat * sb,unsigned flag)245 static inline int ext2_setflag(int fd, struct stat *sb, unsigned flag)
246 {
247   if (!S_ISREG(sb->st_mode) && !S_ISDIR(sb->st_mode)) {
248     errno = EOPNOTSUPP;
249     return -1;
250   }
251   return (ioctl(fd, FS_IOC_SETFLAGS, (void*)&flag));
252 }
253 
get_flag_val(char ch)254 static unsigned get_flag_val(char ch)
255 {
256   struct ext2_attr *ptr = e2attrs;
257 
258   for (; ptr->name; ptr++) if (ptr->opt == ch) return ptr->flag;
259   help_exit("bad '%c'", ch);
260 }
261 
262 // Parse command line argument and fill the chattr structure.
parse_cmdline_arg(char *** argv)263 static void parse_cmdline_arg(char ***argv)
264 {
265   char *arg = **argv, *ptr;
266 
267   while (arg) {
268     switch (arg[0]) {
269       case '-':
270         for (ptr = ++arg; *ptr; ptr++)
271           TT.rm |= get_flag_val(*ptr);
272         break;
273       case '+':
274         for (ptr = ++arg; *ptr; ptr++)
275           TT.add |= get_flag_val(*ptr);
276         break;
277       case '=':
278         TT.have_set = 1;
279         for (ptr = ++arg; *ptr; ptr++)
280           TT.set |= get_flag_val(*ptr);
281         break;
282       default: return;
283     }
284     arg = *(*argv += 1);
285   }
286 }
287 
288 // Update attribute of given file.
update_attr(struct dirtree * root)289 static int update_attr(struct dirtree *root)
290 {
291   char *fpath = NULL;
292   int vv = TT.v, fd;
293 
294   if (!dirtree_notdotdot(root)) return 0;
295 
296   /*
297    * if file is a link and recursive is set or file is not regular+link+dir
298    * (like fifo or dev file) then escape the file.
299    */
300   if ((S_ISLNK(root->st.st_mode) && FLAG(R))
301     || (!S_ISREG(root->st.st_mode) && !S_ISLNK(root->st.st_mode)
302       && !S_ISDIR(root->st.st_mode)))
303     return 0;
304 
305   fpath = dirtree_path(root, NULL);
306   if (-1 == (fd=open(fpath, O_RDONLY | O_NONBLOCK))) {
307     free(fpath);
308     return DIRTREE_ABORT;
309   }
310 
311   // Any potential flag changes?
312   if (TT.have_set | TT.add | TT.rm) {
313     unsigned orig, new;
314 
315     // Read current flags.
316     if (ext2_getflag(fd, &(root->st), &orig) < 0) {
317       perror_msg("read flags of '%s'", fpath);
318       free(fpath);
319       xclose(fd);
320       return DIRTREE_ABORT;
321     }
322     // Apply the requested changes.
323     if (TT.have_set) new = TT.set; // '='.
324     else { // '-' and/or '+'.
325       new = orig;
326       new &= ~(TT.rm);
327       new |= TT.add;
328       if (!S_ISDIR(root->st.st_mode)) new &= ~FS_DIRSYNC_FL;
329     }
330     // Write them back if there was any change.
331     if (orig != new && ext2_setflag(fd, &(root->st), new)<0)
332       perror_msg("%s: setting flags to =%s failed", fpath, attrstr(new, 0));
333   }
334 
335   // (FS_IOC_SETVERSION works all the way back to 2.6, but FS_IOC_FSSETXATTR
336   // isn't available until 4.5.)
337   if (FLAG(v) && (ioctl(fd, FS_IOC_SETVERSION, &vv)<0))
338     perror_msg("%s: setting version to %d failed", fpath, vv);
339 
340   if (FLAG(p)) {
341     struct fsxattr fsx;
342     int fail = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
343 
344     fsx.fsx_projid = TT.p;
345     if (fail || ioctl(fd, FS_IOC_FSSETXATTR, &fsx))
346       perror_msg("%s: setting projid to %u failed", fpath, fsx.fsx_projid);
347   }
348 
349   free(fpath);
350   xclose(fd);
351   return (FLAG(R) && S_ISDIR(root->st.st_mode)) ? DIRTREE_RECURSE : 0;
352 }
353 
chattr_main(void)354 void chattr_main(void)
355 {
356   char **argv = toys.optargs;
357 
358   parse_cmdline_arg(&argv);
359   if (TT.p < 0 || TT.p > UINT_MAX) error_exit("bad projid %lu", TT.p);
360   if (TT.v < 0 || TT.v > UINT_MAX) error_exit("bad version %ld", TT.v);
361   if (!*argv) help_exit("no file");
362   if (TT.have_set && (TT.add || TT.rm))
363     error_exit("no '=' with '-' or '+'");
364   if (TT.rm & TT.add) error_exit("set/unset same flag");
365   if (!(TT.add || TT.rm || TT.have_set || FLAG(p) || FLAG(v)))
366     error_exit("need '-p', '-v', '=', '-', or '+'");
367   for (; *argv; argv++) dirtree_read(*argv, update_attr);
368 }
369