1 /* makedevs.c - Make ranges of device files.
3 * Copyright 2014 Bilal Qureshi <bilal.jmi@gmail.com>
4 * Copyright 2014 Kyungwan Han <asura321@gmail.com>
8 USE_MAKEDEVS(NEWTOY(makedevs, "<1>1d:", TOYFLAG_USR|TOYFLAG_BIN))
14 usage: makedevs [-d device_table] rootdir
16 Create a range of special files as specified in a device table.
18 -d file containing device table (default reads from stdin)
20 Each line of of the device table has the fields:
21 <name> <type> <mode> <uid> <gid> <major> <minor> <start> <increment> <count>
22 Where name is the file name, and type is one of the following:
30 Other fields specify permissions, user and group id owning the file,
31 and additional fields for device special files. Use '-' for blank entries,
32 unspecified fields are treated as '-'.
44 int fd = 0, line_no, i;
47 // Open file and chdir, verbosely
48 xprintf("rootdir = %s\n", *toys.optargs);
49 if (toys.optflags & FLAG_d && strcmp(TT.fname, "-")) {
50 fd = xopenro(TT.fname);
51 xprintf("table = %s\n", TT.fname);
52 } else xprintf("table = <stdin>\n");
53 xchdir(*toys.optargs);
55 for (line_no = 0; (line = get_line(fd)); free(line)) {
56 char type=0, user[64], group[64], *node, *ptr = line;
57 unsigned int mode = 0755, major = 0, minor = 0, cnt = 0, incr = 0,
64 while (isspace(*ptr)) ptr++;
65 if (!*ptr || *ptr == '#') continue;
68 while (*ptr && !isspace(*ptr)) ptr++;
69 if (*ptr) *(ptr++) = 0;
71 sscanf(ptr, "%c %o %63s %63s %u %u %u %u %u", &type, &mode,
72 user, group, &major, &minor, &st_val, &incr, &cnt);
74 // type order here needs to line up with actions[] order.
75 i = stridx("pcbdf", type);
77 error_msg("line %d: bad type %c", line_no, type);
79 } else mode |= (mode_t[]){S_IFIFO, S_IFCHR, S_IFBLK, 0, 0}[i];
81 uid = *user ? xgetuid(user) : getuid();
82 gid = *group ? xgetgid(group) : getgid();
84 while (*node == '/') node++; // using relative path
86 for (i = 0; (!cnt && !i) || i < cnt; i++) {
88 snprintf(toybuf, sizeof(toybuf), "%.999s%u", node, st_val + i);
93 if (mkpathat(AT_FDCWD, ptr, mode, 3)) {
94 perror_msg("can't create directory '%s'", ptr);
97 } else if (type == 'f') {
98 if (stat(ptr, &st) || !S_ISREG(st.st_mode)) {
99 perror_msg("line %d: file '%s' does not exist", line_no, ptr);
102 } else if (mknod(ptr, mode, dev_makedev(major, minor + i*incr))) {
103 perror_msg("line %d: can't create node '%s'", line_no, ptr);
107 if (chown(ptr, uid, gid) || chmod(ptr, mode))
108 perror_msg("line %d: can't chown/chmod '%s'", line_no, ptr);