2 * Copyright (c) 2014 by David I. Bell
3 * Permission is granted to use, distribute, or modify this source,
4 * provided that this copyright notice remains intact.
6 * The "chattr" and "lsattr" built-in commands.
7 * These commands are optionally built into sash.
8 * They manipulate the important ext2 file system file attribute flags.
13 #include <sys/ioctl.h>
14 #include <sys/types.h>
17 * These were used for old linux versions.
18 * #include <linux/fs.h>
19 * #include <linux/ext2_fs.h>
22 #include <ext2fs/ext2_fs.h>
30 * This can turn on or off the immutable and append-only ext2 flags.
33 do_chattr(int argc, const char ** argv)
35 const char * fileName;
55 while ((**argv == '-') || (**argv == '+'))
61 * Point at the proper flags to be modified.
63 if (*options++ == '+')
64 flagPointer = &onFlags;
66 flagPointer = &offFlags;
69 * Parse the flag characters.
76 *flagPointer |= EXT2_IMMUTABLE_FL;
80 *flagPointer |= EXT2_APPEND_FL;
84 fprintf(stderr, "Unknown flag '%c'\n",
93 * Make sure that the attributes are reasonable.
95 if ((onFlags == 0) && (offFlags == 0))
97 fprintf(stderr, "No attributes specified\n");
102 if ((onFlags & offFlags) != 0)
104 fprintf(stderr, "Inconsistent attributes specified\n");
110 * Make sure there are some files to affect.
114 fprintf(stderr, "No files specified for setting attributes\n");
120 * Iterate over all of the file names.
127 * Open the file name.
129 fd = open(fileName, O_RDONLY | O_NONBLOCK);
139 * Read the current ext2 flag bits.
141 if (ioctl(fd, EXT2_IOC_GETFLAGS, &oldFlags) < 0)
151 * Modify the flag bits as specified.
155 newFlags &= ~offFlags;
158 * If the flags aren't being changed, then close this
161 if (newFlags == oldFlags)
169 * Set the new ext2 flag bits.
171 if (ioctl(fd, EXT2_IOC_SETFLAGS, &newFlags) < 0)
191 * The lsattr command.
192 * This lists the immutable and append-only ext2 flags.
195 do_lsattr(int argc, const char ** argv)
197 const char * fileName;
209 * Iterate over all of the file names.
216 * Open the file name.
218 fd = open(fileName, O_RDONLY | O_NONBLOCK);
228 * Read the ext2 flag bits.
230 status = ioctl(fd, EXT2_IOC_GETFLAGS, &flags);
233 * Close the file and check the status.
246 * Build up the string according to the flags.
247 * This is 'i' for immutable, and 'a' for append only.
249 string[0] = ((flags & EXT2_IMMUTABLE_FL) ? 'i' : '-');
250 string[1] = ((flags & EXT2_APPEND_FL) ? 'a' : '-');
254 * Print the flags and the file name.
256 printf("%s %s\n", string, fileName);