1 /* vi: set sw=4 ts=4: */
2 /*
3  *  This program is free software; you can redistribute it and/or modify
4  *  it under the terms of the GNU General Public License version 2 as
5  *  published by the Free Software Foundation.
6  *
7  *  This program is distributed in the hope that it will be useful,
8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *  GNU Library General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  *
16  */
17 
18 #define _GNU_SOURCE
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <fcntl.h>
23 #include <getopt.h>
24 #include <time.h>
25 #include <pwd.h>
26 #include <grp.h>
27 #include <unistd.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <libgen.h>
31 #include <stdarg.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #ifndef __APPLE__
35 #include <sys/sysmacros.h>     /* major() and minor() */
36 #endif
37 #include <ftw.h>
38 #ifdef EXTENDED_ATTRIBUTES
39 #include <sys/capability.h>
40 #endif /* EXTENDED_ATTRIBUTES */
41 
42 const char *bb_applet_name;
43 uid_t recursive_uid;
44 gid_t recursive_gid;
45 unsigned int recursive_mode;
46 #define PASSWD_PATH "etc/passwd"  /* MUST be relative */
47 #define GROUP_PATH "etc/group"  /* MUST be relative */
48 
bb_verror_msg(const char * s,va_list p)49 void bb_verror_msg(const char *s, va_list p)
50 {
51 	fflush(stdout);
52 	fprintf(stderr, "%s: ", bb_applet_name);
53 	vfprintf(stderr, s, p);
54 }
55 
bb_error_msg(const char * s,...)56 void bb_error_msg(const char *s, ...)
57 {
58 	va_list p;
59 
60 	va_start(p, s);
61 	bb_verror_msg(s, p);
62 	va_end(p);
63 	putc('\n', stderr);
64 }
65 
bb_error_msg_and_die(const char * s,...)66 void bb_error_msg_and_die(const char *s, ...)
67 {
68 	va_list p;
69 
70 	va_start(p, s);
71 	bb_verror_msg(s, p);
72 	va_end(p);
73 	putc('\n', stderr);
74 	exit(1);
75 }
76 
bb_vperror_msg(const char * s,va_list p)77 void bb_vperror_msg(const char *s, va_list p)
78 {
79 	int err=errno;
80 	if(s == 0) s = "";
81 	bb_verror_msg(s, p);
82 	if (*s) s = ": ";
83 	fprintf(stderr, "%s%s\n", s, strerror(err));
84 }
85 
bb_perror_msg(const char * s,...)86 void bb_perror_msg(const char *s, ...)
87 {
88 	va_list p;
89 
90 	va_start(p, s);
91 	bb_vperror_msg(s, p);
92 	va_end(p);
93 }
94 
bb_perror_msg_and_die(const char * s,...)95 void bb_perror_msg_and_die(const char *s, ...)
96 {
97 	va_list p;
98 
99 	va_start(p, s);
100 	bb_vperror_msg(s, p);
101 	va_end(p);
102 	exit(1);
103 }
104 
bb_xfopen(const char * path,const char * mode)105 FILE *bb_xfopen(const char *path, const char *mode)
106 {
107 	FILE *fp;
108 	if ((fp = fopen(path, mode)) == NULL)
109 		bb_perror_msg_and_die("%s", path);
110 	return fp;
111 }
112 
113 enum {
114 	FILEUTILS_PRESERVE_STATUS = 1,
115 	FILEUTILS_DEREFERENCE = 2,
116 	FILEUTILS_RECUR = 4,
117 	FILEUTILS_FORCE = 8,
118 	FILEUTILS_INTERACTIVE = 16
119 };
bb_make_directory(char * path,long mode,int flags)120 int bb_make_directory (char *path, long mode, int flags)
121 {
122 	mode_t mask;
123 	const char *fail_msg;
124 	char *s = path;
125 	char c;
126 	struct stat st;
127 
128 	mask = umask(0);
129 	if (mode == -1) {
130 		umask(mask);
131 		mode = (S_IXUSR | S_IXGRP | S_IXOTH |
132 				S_IWUSR | S_IWGRP | S_IWOTH |
133 				S_IRUSR | S_IRGRP | S_IROTH) & ~mask;
134 	} else {
135 		umask(mask & ~0300);
136 	}
137 
138 	do {
139 		c = 0;
140 
141 		if (flags & FILEUTILS_RECUR) {	/* Get the parent. */
142 			/* Bypass leading non-'/'s and then subsequent '/'s. */
143 			while (*s) {
144 				if (*s == '/') {
145 					do {
146 						++s;
147 					} while (*s == '/');
148 					c = *s;		/* Save the current char */
149 					*s = 0;		/* and replace it with nul. */
150 					break;
151 				}
152 				++s;
153 			}
154 		}
155 
156 		if (mkdir(path, 0777) < 0) {
157 			/* If we failed for any other reason than the directory
158 			 * already exists, output a diagnostic and return -1.*/
159 			if ((errno != EEXIST && errno != EISDIR)
160 					|| !(flags & FILEUTILS_RECUR)
161 					|| (stat(path, &st) < 0 || !S_ISDIR(st.st_mode))) {
162 				fail_msg = "create";
163 				umask(mask);
164 				break;
165 			}
166 			/* Since the directory exists, don't attempt to change
167 			 * permissions if it was the full target.  Note that
168 			 * this is not an error conditon. */
169 			if (!c) {
170 				umask(mask);
171 				return 0;
172 			}
173 		}
174 
175 		if (!c) {
176 			/* Done.  If necessary, updated perms on the newly
177 			 * created directory.  Failure to update here _is_
178 			 * an error.*/
179 			umask(mask);
180 			if ((mode != -1) && (chmod(path, mode) < 0)){
181 				fail_msg = "set permissions of";
182 				break;
183 			}
184 			return 0;
185 		}
186 
187 		/* Remove any inserted nul from the path (recursive mode). */
188 		*s = c;
189 
190 	} while (1);
191 
192 	bb_perror_msg ("Cannot %s directory `%s'", fail_msg, path);
193 	return -1;
194 }
195 
196 const char * const bb_msg_memory_exhausted = "memory exhausted";
197 
xmalloc(size_t size)198 void *xmalloc(size_t size)
199 {
200 	void *ptr = malloc(size);
201 	if (ptr == NULL && size != 0)
202 		bb_error_msg_and_die(bb_msg_memory_exhausted);
203 	return ptr;
204 }
205 
xcalloc(size_t nmemb,size_t size)206 void *xcalloc(size_t nmemb, size_t size)
207 {
208 	void *ptr = calloc(nmemb, size);
209 	if (ptr == NULL && nmemb != 0 && size != 0)
210 		bb_error_msg_and_die(bb_msg_memory_exhausted);
211 	return ptr;
212 }
213 
xrealloc(void * ptr,size_t size)214 void *xrealloc(void *ptr, size_t size)
215 {
216 	ptr = realloc(ptr, size);
217 	if (ptr == NULL && size != 0)
218 		bb_error_msg_and_die(bb_msg_memory_exhausted);
219 	return ptr;
220 }
221 
private_get_line_from_file(FILE * file,int c)222 char *private_get_line_from_file(FILE *file, int c)
223 {
224 #define GROWBY (80)		/* how large we will grow strings by */
225 
226 	int ch;
227 	int idx = 0;
228 	char *linebuf = NULL;
229 	int linebufsz = 0;
230 
231 	while ((ch = getc(file)) != EOF) {
232 		/* grow the line buffer as necessary */
233 		if (idx > linebufsz - 2) {
234 			linebuf = xrealloc(linebuf, linebufsz += GROWBY);
235 		}
236 		linebuf[idx++] = (char)ch;
237 		if (!ch) return linebuf;
238 		if (c<2 && ch == '\n') {
239 			if (c) {
240 				--idx;
241 			}
242 			break;
243 		}
244 	}
245 	if (linebuf) {
246 		if (ferror(file)) {
247 			free(linebuf);
248 			return NULL;
249 		}
250 		linebuf[idx] = 0;
251 	}
252 	return linebuf;
253 }
254 
bb_get_chomped_line_from_file(FILE * file)255 char *bb_get_chomped_line_from_file(FILE *file)
256 {
257 	return private_get_line_from_file(file, 1);
258 }
259 
my_getpwnam(const char * name)260 long my_getpwnam(const char *name)
261 {
262 	struct passwd *myuser;
263 	FILE *stream;
264 
265 	stream = bb_xfopen(PASSWD_PATH, "r");
266 	while(1) {
267 		errno = 0;
268 		myuser = fgetpwent(stream);
269 		if (myuser == NULL)
270 			bb_error_msg_and_die("unknown user name: %s", name);
271 		if (errno)
272 			bb_perror_msg_and_die("fgetpwent");
273 		if (!strcmp(name, myuser->pw_name))
274 			break;
275 	}
276 	fclose(stream);
277 
278 	return myuser->pw_uid;
279 }
280 
my_getgrnam(const char * name)281 long my_getgrnam(const char *name)
282 {
283 	struct group *mygroup;
284 	FILE *stream;
285 
286 	stream = bb_xfopen(GROUP_PATH, "r");
287 	while(1) {
288 		errno = 0;
289 		mygroup = fgetgrent(stream);
290 		if (mygroup == NULL)
291 			bb_error_msg_and_die("unknown group name: %s", name);
292 		if (errno)
293 			bb_perror_msg_and_die("fgetgrent");
294 		if (!strcmp(name, mygroup->gr_name))
295 			break;
296 	}
297 	fclose(stream);
298 
299 	return mygroup->gr_gid;
300 }
301 
get_ug_id(const char * s,long (* my_getxxnam)(const char *))302 unsigned long get_ug_id(const char *s, long (*my_getxxnam)(const char *))
303 {
304 	unsigned long r;
305 	char *p;
306 
307 	r = strtoul(s, &p, 10);
308 	if (*p || (s == p)) {
309 		r = my_getxxnam(s);
310 	}
311 
312 	return r;
313 }
314 
last_char_is(const char * s,int c)315 char * last_char_is(const char *s, int c)
316 {
317 	char *sret = (char *)s;
318 	if (sret) {
319 		sret = strrchr(sret, c);
320 		if(sret != NULL && *(sret+1) != 0)
321 			sret = NULL;
322 	}
323 	return sret;
324 }
325 
bb_xasprintf(char ** string_ptr,const char * format,...)326 void bb_xasprintf(char **string_ptr, const char *format, ...)
327 {
328 	va_list p;
329 	int r;
330 
331 	va_start(p, format);
332 	r = vasprintf(string_ptr, format, p);
333 	va_end(p);
334 
335 	if (r < 0) {
336 		bb_perror_msg_and_die("bb_xasprintf");
337 	}
338 }
339 
concat_path_file(const char * path,const char * filename)340 char *concat_path_file(const char *path, const char *filename)
341 {
342 	char *outbuf;
343 	char *lc;
344 
345 	if (!path)
346 		path = "";
347 	lc = last_char_is(path, '/');
348 	while (*filename == '/')
349 		filename++;
350 	bb_xasprintf(&outbuf, "%s%s%s", path, (lc==NULL ? "/" : ""), filename);
351 
352 	return outbuf;
353 }
354 
355 #ifdef EXTENDED_ATTRIBUTES
bb_set_xattr(const char * fpath,const char * xattr)356 int bb_set_xattr(const char *fpath, const char *xattr)
357 {
358 	cap_t cap, cap_file, cap_new;
359 	char *cap_file_text, *cap_new_text;
360 	ssize_t length;
361 
362 	cap = cap_from_text(xattr);
363 	if (cap == NULL)
364 		bb_perror_msg_and_die("cap_from_text failed for %s", xattr);
365 
366 	cap_file = cap_get_file(fpath);
367 	if (cap_file == NULL) {
368 		/* if no capability was set before, we initialize cap_file */
369 		if (errno != ENODATA)
370 			bb_perror_msg_and_die("cap_get_file failed on %s", fpath);
371 
372 		cap_file = cap_init();
373 		if (!cap_file)
374 			bb_perror_msg_and_die("cap_init failed");
375 	}
376 
377 	if ((cap_file_text = cap_to_text(cap_file, &length)) == NULL)
378 		bb_perror_msg_and_die("cap_to_name failed on %s", fpath);
379 
380 	bb_xasprintf(&cap_new_text, "%s %s", cap_file_text, xattr);
381 
382 	if ((cap_new = cap_from_text(cap_new_text)) == NULL)
383 		bb_perror_msg_and_die("cap_from_text failed on %s", cap_new_text);
384 
385 	if (cap_set_file(fpath, cap_new) == -1)
386 		bb_perror_msg_and_die("cap_set_file failed for %s (xattr = %s)", fpath, xattr);
387 
388 	cap_free(cap);
389 	cap_free(cap_file);
390 	cap_free(cap_file_text);
391 	cap_free(cap_new);
392 	cap_free(cap_new_text);
393 
394 	return 0;
395 }
396 #endif /* EXTENDED_ATTRIBUTES */
397 
bb_show_usage(void)398 void bb_show_usage(void)
399 {
400 	fprintf(stderr, "%s: [-d device_table] rootdir\n\n", bb_applet_name);
401 	fprintf(stderr, "Creates a batch of special files as specified in a device table.\n");
402 	fprintf(stderr, "Device table entries take the form of:\n");
403 	fprintf(stderr, "name type mode user group major minor start increment count\n\n");
404 	fprintf(stderr, "Where name is the file name,  type can be one of:\n");
405 	fprintf(stderr, "      f       A regular file\n");
406 	fprintf(stderr, "      d       Directory\n");
407 	fprintf(stderr, "      r       Directory recursively\n");
408 	fprintf(stderr, "      c       Character special device file\n");
409 	fprintf(stderr, "      b       Block special device file\n");
410 	fprintf(stderr, "      p       Fifo (named pipe)\n");
411 	fprintf(stderr, "uid is the user id for the target file, gid is the group id for the\n");
412 	fprintf(stderr, "target file.  The rest of the entries (major, minor, etc) apply to\n");
413 	fprintf(stderr, "to device special files.  A '-' may be used for blank entries.\n\n");
414 	fprintf(stderr, "For example:\n");
415 	fprintf(stderr, "<name>    <type> <mode> <uid> <gid> <major> <minor> <start> <inc> <count>\n");
416 	fprintf(stderr, "/dev         d    755    0    0     -       -       -       -     -\n");
417 	fprintf(stderr, "/dev/console c    666    0    0     5       1       -       -     -\n");
418 	fprintf(stderr, "/dev/null    c    666    0    0     1       3       0       0     -\n");
419 	fprintf(stderr, "/dev/zero    c    666    0    0     1       5       0       0     -\n");
420 	fprintf(stderr, "/dev/hda     b    640    0    0     3       0       0       0     -\n");
421 	fprintf(stderr, "/dev/hda     b    640    0    0     3       1       1       1     15\n");
422 	fprintf(stderr, "/dev/rtp     b    640    0    0     250     0       0       1     5\n");
423 	fprintf(stderr, "/dev/gps     b    640    0    0     251     0       1       1     5\n");
424 	fprintf(stderr, "/dev/uio     b    640    0    0     252     0       1       2     5\n");
425 	fprintf(stderr, "/dev/uio     b    640    0    0     252     1       6       2     5\n\n");
426 	fprintf(stderr, "Will Produce:\n");
427 	fprintf(stderr, "/dev\n");
428 	fprintf(stderr, "/dev/console\n");
429 	fprintf(stderr, "/dev/null\n");
430 	fprintf(stderr, "/dev/zero\n");
431 	fprintf(stderr, "/dev/hda\n");
432 	fprintf(stderr, "/dev/hda[1-15] with minor numbers [1-15]\n");
433 	fprintf(stderr, "/dev/rtp[0-4]  with minor numbers [0-4]\n");
434 	fprintf(stderr, "/dev/gps[1-5]  with minor numbers [0-4]\n");
435 	fprintf(stderr, "/dev/uio[1-5]  with minor numbers 0,2,4,6,8\n");
436 	fprintf(stderr, "/dev/uio[6-10] with minor numbers 1,3,5,7,9\n");
437 	exit(1);
438 }
439 
bb_recursive(const char * fpath,const struct stat * sb,int tflag,struct FTW * ftwbuf)440 int bb_recursive(const char *fpath, const struct stat *sb,
441 		int tflag, struct FTW *ftwbuf){
442 
443 	if (lchown(fpath, recursive_uid, recursive_gid) == -1) {
444 		bb_perror_msg("chown failed for %s", fpath);
445 		return -1;
446 	}
447 
448 	/* chmod() is optional, also skip if dangling symlink */
449 	if (recursive_mode == -1 || (tflag == FTW_SL && !access(fpath, F_OK)))
450 		return 0;
451 
452 	if (chmod(fpath, recursive_mode) < 0) {
453 		bb_perror_msg("chmod failed for %s", fpath);
454 		return -1;
455 	}
456 
457 	return 0;
458 }
459 
main(int argc,char ** argv)460 int main(int argc, char **argv)
461 {
462 	int opt;
463 	FILE *table = stdin;
464 	char *rootdir = NULL;
465 	char *full_name = NULL;
466 	char *line = NULL;
467 	int linenum = 0;
468 	int ret = EXIT_SUCCESS;
469 
470 	bb_applet_name = basename(argv[0]);
471 
472 	while ((opt = getopt(argc, argv, "d:")) != -1) {
473 		switch(opt) {
474 			case 'd':
475 				table = bb_xfopen((line=optarg), "r");
476 				break;
477 			default:
478 				bb_show_usage();
479 		}
480 	}
481 
482 	if (optind >= argc || (rootdir=argv[optind])==NULL) {
483 		bb_error_msg_and_die("root directory not speficied");
484 	}
485 
486 	if (chdir(rootdir) != 0) {
487 		bb_perror_msg_and_die("Couldnt chdir to %s", rootdir);
488 	}
489 
490 	umask(0);
491 
492 	printf("rootdir=%s\n", rootdir);
493 	if (line) {
494 		printf("table='%s'\n", line);
495 	} else {
496 		printf("table=<stdin>\n");
497 	}
498 
499 	while ((line = bb_get_chomped_line_from_file(table))) {
500 		char type;
501 		unsigned int mode = 0755;
502 		unsigned int major = 0;
503 		unsigned int minor = 0;
504 		unsigned int count = 0;
505 		unsigned int increment = 0;
506 		unsigned int start = 0;
507 		char xattr[255];
508 		char name[4096];
509 		char user[41];
510 		char group[41];
511 		uid_t uid;
512 		gid_t gid;
513 
514 		linenum++;
515 
516 		if (1 == sscanf(line, " |xattr %254s", xattr)) {
517 #ifdef EXTENDED_ATTRIBUTES
518 			if (!full_name)
519 				bb_error_msg_and_die("line %d should be after a file\n", linenum);
520 
521 			if (bb_set_xattr(full_name, xattr) < 0)
522 				bb_error_msg_and_die("can't set cap %s on file %s\n", xattr, full_name);
523 #else
524 			bb_error_msg_and_die("line %d not supported: '%s'\nDid you forget to enable "
525 					     "BR2_ROOTFS_DEVICE_TABLE_SUPPORTS_EXTENDED_ATTRIBUTES?\n",
526 					     linenum, line);
527 #endif /* EXTENDED_ATTRIBUTES */
528 			continue;
529 		}
530 
531 		if ((2 > sscanf(line, "%4095s %c %o %40s %40s %u %u %u %u %u", name,
532 						&type, &mode, user, group, &major,
533 						&minor, &start, &increment, &count)) ||
534 				((major | minor | start | count | increment) > 0xfffff))
535 		{
536 			if (*line=='\0' || *line=='#' || isspace(*line))
537 				continue;
538 			bb_error_msg("line %d invalid: '%s'\n", linenum, line);
539 			ret = EXIT_FAILURE;
540 			continue;
541 		}
542 		if (name[0] == '#') {
543 			continue;
544 		}
545 		if (*group) {
546 			gid = get_ug_id(group, my_getgrnam);
547 		} else {
548 			gid = getgid();
549 		}
550 		if (*user) {
551 			uid = get_ug_id(user, my_getpwnam);
552 		} else {
553 			uid = getuid();
554 		}
555 
556 		/*
557 		 * free previous full name
558 		 * we don't de-allocate full_name at the end of the parsing,
559 		 * because we may need it if the next line is an xattr.
560 		 */
561 		free(full_name);
562 		full_name = concat_path_file(rootdir, name);
563 
564 		if (type == 'd') {
565 			bb_make_directory(full_name, mode | S_IFDIR, FILEUTILS_RECUR);
566 			if (chown(full_name, uid, gid) == -1) {
567 				bb_perror_msg("line %d: chown failed for %s", linenum, full_name);
568 				ret = EXIT_FAILURE;
569 				goto loop;
570 			}
571 			if ((mode != -1) && (chmod(full_name, mode) < 0)){
572 				bb_perror_msg("line %d: chmod failed for %s", linenum, full_name);
573 				ret = EXIT_FAILURE;
574 				goto loop;
575 			}
576 		} else if (type == 'f' || type == 'F') {
577 			struct stat st;
578 			if ((stat(full_name, &st) < 0 || !S_ISREG(st.st_mode))) {
579 				if (type == 'F') {
580 					continue; /*Ignore optional files*/
581 				}
582 				bb_perror_msg("line %d: regular file '%s' does not exist", linenum, full_name);
583 				ret = EXIT_FAILURE;
584 				goto loop;
585 			}
586 			if (chown(full_name, uid, gid) == -1) {
587 				bb_perror_msg("line %d: chown failed for %s", linenum, full_name);
588 				ret = EXIT_FAILURE;
589 				goto loop;
590 			}
591 			if ((mode != -1) && (chmod(full_name, mode) < 0)){
592 				bb_perror_msg("line %d: chmod failed for %s", linenum, full_name);
593 				ret = EXIT_FAILURE;
594 				goto loop;
595 			}
596 		} else if (type == 'r') {
597 			recursive_uid = uid;
598 			recursive_gid = gid;
599 			recursive_mode = mode;
600 			if (nftw(full_name, bb_recursive, 20, FTW_MOUNT | FTW_PHYS) < 0) {
601 				bb_perror_msg("line %d: recursive failed for %s", linenum, full_name);
602 				ret = EXIT_FAILURE;
603 				goto loop;
604 			}
605 		} else
606 		{
607 			dev_t rdev;
608 			unsigned i;
609 			char *full_name_inc;
610 
611 			if (type == 'p') {
612 				mode |= S_IFIFO;
613 			}
614 			else if (type == 'c') {
615 				mode |= S_IFCHR;
616 			}
617 			else if (type == 'b') {
618 				mode |= S_IFBLK;
619 			} else {
620 				bb_error_msg("line %d: Unsupported file type %c", linenum, type);
621 				ret = EXIT_FAILURE;
622 				goto loop;
623 			}
624 
625 			full_name_inc = xmalloc(strlen(full_name) + sizeof(int)*3 + 2);
626 			if (count)
627 				count--;
628 			for (i = start; i <= start + count; i++) {
629 				sprintf(full_name_inc, count ? "%s%u" : "%s", full_name, i);
630 				rdev = makedev(major, minor + (i - start) * increment);
631 				if (mknod(full_name_inc, mode, rdev) < 0) {
632 					bb_perror_msg("line %d: can't create node %s", linenum, full_name_inc);
633 					ret = EXIT_FAILURE;
634 				} else if (lchown(full_name_inc, uid, gid) < 0) {
635 					bb_perror_msg("line %d: can't chown %s", linenum, full_name_inc);
636 					ret = EXIT_FAILURE;
637 				} else if (chmod(full_name_inc, mode) < 0) {
638 					bb_perror_msg("line %d: can't chmod %s", linenum, full_name_inc);
639 					ret = EXIT_FAILURE;
640 				}
641 			}
642 			free(full_name_inc);
643 		}
644 loop:
645 		free(line);
646 	}
647 	fclose(table);
648 
649 	return ret;
650 }
651